Skip to content

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

Add view options to Query (#49447)

Saxon Fletcherde2a7d8d9e8e
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
index 75e54ee251a..0acfebf9b16 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
@@ -5,7 +5,7 @@ import { useCallback, useContext, useEffect, useState } from 'react'
import { Button } from 'ui'
import { QueryEditor, type ExplorerQueryModel } from './QueryEditor'
-import { type QueryResult } from './types'
+import { type QueryDisplay, type QueryResult } from './types'
import { toQuerySourceBinding } from '@/data/query-sources/query-source-registry'
import { explorerQueryState, useExplorerQueryStateSnapshot } from '@/state/explorer-query'
import { useControlledRoleImpersonationState } from '@/state/role-impersonation-state'
@@ -71,15 +71,11 @@ export const ExplorerQueryTab = () => {
)
}
- const handleResultChange = (nextResult: QueryResult) => {
- explorerQueryState.setResult({
- id,
- result: { ...nextResult, executedAt: Date.now() },
- })
+ const display: QueryDisplay = {
+ view: draft.view,
+ chart: draft.chart ? { ...draft.chart, y_series: [...draft.chart.y_series] } : undefined,
}
- const persistTab = () => tabs.makeTabPermanent(createTabId('query', { id }))
-
const query: ExplorerQueryModel =
draft._tag === 'logs'
? { ...toQuerySourceBinding(draft), uncheckedSql: draft.uncheckedSql }
@@ -89,6 +85,15 @@ export const ExplorerQueryTab = () => {
rowLimit: draft.rowLimit,
}
+ const persistTab = () => tabs.makeTabPermanent(createTabId('query', { id }))
+
+ const handleResultChange = (nextResult: QueryResult) => {
+ explorerQueryState.setResult({
+ id,
+ result: { ...nextResult, executedAt: Date.now() },
+ })
+ }
+
return (
<QueryEditor
id={id}
@@ -96,6 +101,7 @@ export const ExplorerQueryTab = () => {
title={draft.name}
query={query}
result={result}
+ display={display}
showQuery={showQuery}
onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
@@ -118,6 +124,10 @@ export const ExplorerQueryTab = () => {
explorerQueryState.updateDraft({ id, rowLimit })
}}
onResultChange={handleResultChange}
+ onDisplayChange={(display) => {
+ persistTab()
+ explorerQueryState.setDisplay({ id, display })
+ }}
/>
)
}
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx
index 09787e596c7..095ad7af762 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx
@@ -61,7 +61,8 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {
if (!result || (result?.rows && result.rows.length === 0)) {
return (
<NoDataPlaceholder
- className="bg border-0"
+ isFullHeight
+ className="border-0"
size="normal"
message="No results"
description="Your query returned no rows"
@@ -72,7 +73,8 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {
if (!hasConfig) {
return (
<NoDataPlaceholder
- className="bg border-0"
+ isFullHeight
+ className="border-0"
size="normal"
message="Configure your chart"
description="Select your X and Y axis in the display settings"
@@ -81,45 +83,43 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {
}
return (
- <Chart>
- <ChartCard className="rounded-none border-0">
- <ChartContent>
- <div className="h-40">
- {type === 'bar' && (
- <ChartBar
- isFullHeight
- xKey={x_column}
- dataKey={y_series[0]}
- dataKeys={y_series}
- config={chartConfig}
- showXAxis={show_labels}
- showYAxis={show_labels}
- data={resultToRender}
- YAxisProps={{
- scale: effectiveScale === 'log' ? 'log' : 'auto',
- domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,
- tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,
- }}
- />
- )}
- {type === 'line' && (
- <ChartLine
- isFullHeight
- xKey={x_column}
- dataKey={y_series[0]}
- dataKeys={y_series}
- config={chartConfig}
- showXAxis={show_labels}
- showYAxis={show_labels}
- data={resultToRender}
- YAxisProps={{
- scale: effectiveScale === 'log' ? 'log' : 'auto',
- domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,
- tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,
- }}
- />
- )}
- </div>
+ <Chart className="flex flex-grow min-h-0">
+ <ChartCard className="flex flex-grow rounded-none border-0 min-h-0">
+ <ChartContent className="min-h-0 w-full">
+ {type === 'bar' && (
+ <ChartBar
+ isFullHeight
+ xKey={x_column}
+ dataKey={y_series[0]}
+ dataKeys={y_series}
+ config={chartConfig}
+ showXAxis={show_labels}
+ showYAxis={show_labels}
+ data={resultToRender}
+ YAxisProps={{
+ scale: effectiveScale === 'log' ? 'log' : 'auto',
+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,
+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,
+ }}
+ />
+ )}
+ {type === 'line' && (
+ <ChartLine
+ isFullHeight
+ xKey={x_column}
+ dataKey={y_series[0]}
+ dataKeys={y_series}
+ config={chartConfig}
+ showXAxis={show_labels}
+ showYAxis={show_labels}
+ data={resultToRender}
+ YAxisProps={{
+ scale: effectiveScale === 'log' ? 'log' : 'auto',
+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,
+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,
+ }}
+ />
+ )}
</ChartContent>
</ChartCard>
</Chart>
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index 71639aca904..ccafb2762fd 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -183,6 +183,9 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
const rowLimit = query._tag === 'database' ? query.rowLimit : undefined
const databaseIdentifier = query._tag === 'database' ? query.database_identifier : undefined
+ const { x_column, y_series } = display?.chart ?? {}
+ const hasConfig = !!x_column && (y_series ?? []).length > 0
+
const [promptInput, setPromptInput] = useState('')
const [pendingRun, setPendingRun] = useState<{ sql: string; issues: PotentialIssues }>()
const [pendingProposal, setPendingProposal] = useState<PendingProposal | null>(null)
@@ -524,7 +527,10 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
<ExplorerQueryResults
className={cn(
- (result?.rows ?? []).length === 0 ? 'items-center justify-center' : 'overflow-x-auto'
+ variant === 'embedded' ? 'max-h-80' : '',
+ (result?.rows ?? []).length === 0 || (view === 'chart' && !hasConfig)
+ ? 'items-center justify-center'
+ : 'overflow-x-auto'
)}
>
<QueryResultRenderer view={view} result={result} chart={display?.chart} />
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
index 620f468f417..70224e3f4ff 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
@@ -56,6 +56,53 @@ vi.mock('../QueryEditor/QuerySourceMenu', () => ({
),
}))
+vi.mock('../QueryEditor/DisplaySettingsButton', () => ({
+ DisplaySettingsButton: ({
+ display,
+ disabled,
+ onChange,
+ }: {
+ display: { view: 'table' | 'chart' }
+ disabled: boolean
+ onChange: (display: {
+ view: 'table' | 'chart'
+ chart: {
+ type: 'bar'
+ x_column: string
+ y_series: string[]
+ cumulative: boolean
+ scale: 'linear'
+ show_labels: boolean
+ }
+ }) => void
+ }) => (
+ <button
+ aria-label="Result settings"
+ disabled={disabled}
+ tabIndex={0}
+ onClick={() =>
+ onChange({
+ view: 'chart',
+ chart: {
+ type: 'bar',
+ x_column: 'day',
+ y_series: ['requests'],
+ cumulative: false,
+ scale: 'linear',
+ show_labels: true,
+ },
+ })
+ }
+ >
+ {display.view}
+ </button>
+ ),
+}))
+
+vi.mock('../QueryEditor/QueryResultChart', () => ({
+ QueryResultChart: () => <div>Chart results</div>,
+}))
+
const renderQueryTab = (tabsState = createTabsState('default')) =>
customRender(
<TabsStateContext.Provider value={tabsState}>
@@ -127,6 +174,29 @@ describe('QueryTab execution', () => {
expect(requests).toHaveLength(0)
})
+ it('exposes and persists the shared notebook result view options', async () => {
+ createDraft({ _tag: 'database' })
+ explorerQueryState.setResult({
+ id: 'query-test',
+ result: { rows: [{ day: 'Monday', requests: 10 }], executedAt: 1 },
+ })
+
+ renderQueryTab()
+ const settingsButton = await screen.findByRole('button', { name: 'Result settings' })
+ expect(settingsButton).toBeEnabled()
+ expect(settingsButton).toHaveTextContent('table')
+
+ await userEvent.click(settingsButton)
+
+ await waitFor(() =>
+ expect(explorerQueryState.drafts['query-test']).toMatchObject({
+ view: 'chart',
+ chart: { type: 'bar', x_column: 'day', y_series: ['requests'] },
+ })
+ )
+ expect(settingsButton).toHaveTextContent('chart')
+ })
+
it('waits for replicas, then fails closed when the selected database is absent', async () => {
createDraft({ _tag: 'database', database_identifier: 'missing-replica' })
let releaseReplicas: () => void = () => undefined
diff --git a/apps/studio/data/content/notebooks/notebook-schema.ts b/apps/studio/data/content/notebooks/notebook-schema.ts
index 7d4b058ea76..7b746785656 100644
--- a/apps/studio/data/content/notebooks/notebook-schema.ts
+++ b/apps/studio/data/content/notebooks/notebook-schema.ts
@@ -16,7 +16,7 @@ const isoDateTimeSchema = z.string().transform((raw, ctx) => {
export const MAX_CHART_Y_SERIES = 3
-const chartConfigSchema = z.object({
+export const chartConfigSchema = z.object({
type: z.enum(['bar', 'line']),
x_column: z.string(),
y_series: z.array(z.string()).max(MAX_CHART_Y_SERIES),
diff --git a/apps/studio/state/explorer-query.test.ts b/apps/studio/state/explorer-query.test.ts
index d3268a2606f..fed32b9a8a1 100644
--- a/apps/studio/state/explorer-query.test.ts
+++ b/apps/studio/state/explorer-query.test.ts
@@ -234,6 +234,73 @@ describe('explorer query drafts', () => {
expect(state.drafts['query-1']).toMatchObject({ rowLimit: 100 })
})
+ it('persists and restores result display options independently per draft', () => {
+ const storage = createMemoryStorage()
+ const state = createExplorerQueryState(storage)
+
+ state.createDraft({ id: 'query-1', projectRef: 'project-a' })
+ state.createDraft({ id: 'query-2', projectRef: 'project-a' })
+ state.setDisplay({
+ id: 'query-1',
+ display: {
+ view: 'chart',
+ chart: {
+ type: 'line',
+ x_column: 'day',
+ y_series: ['requests'],
+ cumulative: true,
+ scale: 'log',
+ show_labels: true,
+ },
+ },
+ })
+
+ expect(state.drafts['query-1']).toMatchObject({
+ view: 'chart',
+ chart: { type: 'line', x_column: 'day', y_series: ['requests'] },
+ })
+ expect(state.drafts['query-2']).toMatchObject({ view: 'table', chart: undefined })
+
+ const restored = createExplorerQueryState(storage)
+ expect(restored.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)
+ expect(restored.restoreDraft({ id: 'query-2', projectRef: 'project-a' })).toBe(true)
+ expect(restored.drafts['query-1']).toMatchObject({
+ view: 'chart',
+ chart: {
+ type: 'line',
+ x_column: 'day',
+ y_series: ['requests'],
+ cumulative: true,
+ scale: 'log',
+ show_labels: true,
+ },
+ })
+ expect(restored.drafts['query-2']).toMatchObject({ view: 'table', chart: undefined })
+ })
+
+ it('defaults legacy and malformed display options without dropping the draft', () => {
+ const storage = createMemoryStorage()
+ storage.setItem(
+ LOCAL_STORAGE_KEYS.EXPLORER_QUERY_DRAFTS('project-a'),
+ JSON.stringify({
+ 'legacy-query': { name: 'Legacy query', sql: 'select 1', updatedAt: 1 },
+ 'malformed-query': {
+ name: 'Malformed query',
+ sql: 'select 2',
+ updatedAt: 2,
+ view: 'map',
+ chart: { type: 'pie' },
+ },
+ })
+ )
+
+ const state = createExplorerQueryState(storage)
+ expect(state.restoreDraft({ id: 'legacy-query', projectRef: 'project-a' })).toBe(true)
+ expect(state.restoreDraft({ id: 'malformed-query', projectRef: 'project-a' })).toBe(true)
+ expect(state.drafts['legacy-query']).toMatchObject({ view: 'table', chart: undefined })
+ expect(state.drafts['malformed-query']).toMatchObject({ view: 'table', chart: undefined })
+ })
+
it('accepts every row limit the row limit menu can produce', () => {
const storage = createMemoryStorage()
diff --git a/apps/studio/state/explorer-query.ts b/apps/studio/state/explorer-query.ts
index eb15cd9f3bf..8e0836bd6b7 100644
--- a/apps/studio/state/explorer-query.ts
+++ b/apps/studio/state/explorer-query.ts
@@ -4,9 +4,10 @@ import { proxy, ref, snapshot, useSnapshot } from 'valtio'
import { z } from 'zod'
import { DEFAULT_CELL_ROW_LIMIT } from '@/components/interfaces/Explorer/QueryCell/QueryCell.utils'
-import { type QueryResult } from '@/components/interfaces/Explorer/types'
+import { type QueryDisplay, type QueryResult } from '@/components/interfaces/Explorer/types'
import { ROWS_PER_PAGE_OPTIONS } from '@/components/interfaces/SQLEditor/SQLEditor.constants'
import {
+ chartConfigSchema,
type DatabaseSourceParameters,
type LogsSourceParameters,
} from '@/data/content/notebooks/notebook-schema'
@@ -24,6 +25,8 @@ type ExplorerQueryDraftBase = {
projectRef: string
name: string
updatedAt: number
+ view: QueryDisplay['view']
+ chart?: QueryDisplay['chart']
}
/**
@@ -64,7 +67,7 @@ type PersistedExplorerQueryDraft = {
updatedAt: number
rowLimit?: number
role?: ImpersonationRole
-}
+} & QueryDisplay
type PersistedExplorerQueryDrafts = Record<string, PersistedExplorerQueryDraft>
@@ -81,9 +84,12 @@ const persistedDraftSchema = z.object({
source: z.unknown().optional(),
rowLimit: z.unknown().optional(),
role: z.unknown().optional(),
+ view: z.unknown().optional(),
+ chart: z.unknown().optional(),
})
const VALID_ROW_LIMITS = ROWS_PER_PAGE_OPTIONS.map((option) => option.value)
+const queryViewSchema = z.enum(['table', 'chart'])
/**
* Falls back to the default whenever a persisted row limit isn't one of the values the row
@@ -111,7 +117,14 @@ const toDraft = ({
projectRef: string
persisted: PersistedExplorerQueryDraft
}): ExplorerQueryDraft => {
- const base = { id, projectRef, name: persisted.name, updatedAt: persisted.updatedAt }
+ const base = {
+ id,
+ projectRef,
+ name: persisted.name,
+ updatedAt: persisted.updatedAt,
+ view: persisted.view,
+ chart: persisted.chart,
+ }
if (persisted.source._tag === 'logs') {
return {
@@ -153,6 +166,10 @@ const readPersistedDrafts = (storage: StorageLike, projectRef: string) => {
const parsedRole = impersonationRoleSchema.safeParse(draft.data.role)
const role = parsedRole.success ? parsedRole.data : undefined
const rowLimit = rowLimitSchema.parse(draft.data.rowLimit)
+ const parsedView = queryViewSchema.safeParse(draft.data.view)
+ const view = parsedView.success ? parsedView.data : 'table'
+ const parsedChart = chartConfigSchema.safeParse(draft.data.chart)
+ const chart = parsedChart.success ? parsedChart.data : undefined
return [
[
@@ -164,6 +181,8 @@ const readPersistedDrafts = (storage: StorageLike, projectRef: string) => {
updatedAt: draft.data.updatedAt,
role,
rowLimit,
+ view,
+ chart,
},
],
]
@@ -205,6 +224,8 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorage
updatedAt: draft.updatedAt,
rowLimit: draft._tag === 'database' ? draft.rowLimit : undefined,
role: draft._tag === 'database' ? draft.role : undefined,
+ view: draft.view,
+ chart: draft.chart,
}
writePersistedDrafts(storage, draft.projectRef, persisted)
}
@@ -237,6 +258,7 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorage
sql,
updatedAt: Date.now(),
rowLimit,
+ view: 'table',
},
})
@@ -300,6 +322,8 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorage
updatedAt: Date.now(),
rowLimit: rowLimit ?? currentRowLimit,
role: currentRole,
+ view: draft.view,
+ chart: draft.chart,
},
})
@@ -349,6 +373,21 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorage
state.results[id] = ref(result)
},
+ setDisplay: ({ id, display }: { id: string; display: QueryDisplay }) => {
+ const draft = state.drafts[id]
+ if (!draft) return
+
+ const parsedChart = chartConfigSchema.safeParse(display.chart)
+ const updatedDraft: ExplorerQueryDraft = {
+ ...draft,
+ view: queryViewSchema.parse(display.view),
+ chart: parsedChart.success ? parsedChart.data : undefined,
+ updatedAt: Date.now(),
+ }
+ state.drafts[id] = updatedDraft
+ persistDraft(updatedDraft)
+ },
+
/**
* Separate from `updateDraft` because `undefined` is a meaningful value here (clearing
* the impersonated role), whereas `updateDraft`'s optional fields all use `undefined`