:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dashboards): switch a SQL insight's chart type from its dashboard card (#87717)
Vasco de Krijger5c2fd2c7614d
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardSqlDisplayOptions.scss b/frontend/src/lib/components/Cards/InsightCard/DashboardSqlDisplayOptions.scssnew file mode 100644index 000000000000..ef0fead0dc44--- /dev/null+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardSqlDisplayOptions.scss@@ -0,0 +1,5 @@+.DashboardSqlDisplayOptions {+ .LemonCollapsePanel[aria-expanded='true'] > .LemonCollapsePanel__body {+ height: auto !important;+ }+}diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardSqlDisplayOptions.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardSqlDisplayOptions.tsxnew file mode 100644index 000000000000..8f85beb7b260--- /dev/null+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardSqlDisplayOptions.tsx@@ -0,0 +1,187 @@+import './DashboardSqlDisplayOptions.scss'++import { BindLogic, useValues } from 'kea'+import { useCallback, useEffect, useRef, useState } from 'react'+import type { ReactNode } from 'react'++import { DisplayTab } from '~/queries/nodes/DataVisualization/Components/DisplayTab'+import { TableDisplay } from '~/queries/nodes/DataVisualization/Components/TableDisplay'+import {+ DataVisualizationLogicProps,+ dataVisualizationLogic,+ rowCountFromResponse,+} from '~/queries/nodes/DataVisualization/dataVisualizationLogic'+import { displayLogic } from '~/queries/nodes/DataVisualization/displayLogic'+import { applyDataVisualizationQueryUpdate } from '~/queries/nodes/DataVisualization/queryUpdateUtils'+import { sqlVisualizationDisabledReason } from '~/queries/nodes/DataVisualization/sqlVisualizationSupport'+import { AnyResponseType, DataVisualizationNode, HogQLVariable } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++let uniqueNode = 0++interface DashboardSqlVisualizationLogicProps {+ query: DataVisualizationNode+ cachedResults: AnyResponseType+ variablesOverride?: Record<string, HogQLVariable> | null+ persistQuery: (query: DataVisualizationNode) => void+ children: ReactNode+}++function DashboardSqlVisualizationLogic({+ query,+ cachedResults,+ variablesOverride,+ persistQuery,+ children,+}: DashboardSqlVisualizationLogicProps): JSX.Element {+ const [key] = useState(`dashboard-sql-visualization.${uniqueNode++}`)+ const queryRef = useRef(query)+ const queryPropRef = useRef(query)+ const hasMountedRef = useRef(false)++ if (queryPropRef.current !== query) {+ queryPropRef.current = query+ queryRef.current = query+ }++ useEffect(() => {+ hasMountedRef.current = true+ }, [])++ const setQuery = useCallback(+ (setter: Parameters<typeof applyDataVisualizationQueryUpdate>[1]) =>+ applyDataVisualizationQueryUpdate(queryRef, setter, (nextQuery) => {+ if (hasMountedRef.current) {+ persistQuery(nextQuery)+ }+ }),+ [persistQuery]+ )++ const logicProps: DataVisualizationLogicProps = {+ key,+ query: queryRef.current,+ dataNodeCollectionId: key,+ cachedResults,+ variablesOverride,+ setQuery,+ }++ return (+ <BindLogic logic={dataVisualizationLogic} props={logicProps}>+ <BindLogic logic={displayLogic} props={{ key }}>+ {children}+ </BindLogic>+ </BindLogic>+ )+}++function DashboardSqlChartTypeControl({+ disabledReason,+ loading,+ saving,+}: {+ disabledReason?: string+ loading?: boolean+ saving?: boolean+}): JSX.Element {+ const { autoVisualizationType, columns, query, response } = useValues(dataVisualizationLogic)+ const rowCount = rowCountFromResponse(response)+ const disabledReasonFor = useCallback(+ (display: ChartDisplayType): string | undefined =>+ sqlVisualizationDisabledReason(display, query, columns, rowCount, autoVisualizationType),+ [query, columns, rowCount, autoVisualizationType]+ )+ let chartTypeDisabledReason = disabledReason+ if (chartTypeDisabledReason === undefined) {+ if (saving) {+ chartTypeDisabledReason = 'Saving chart type'+ } else if (loading) {+ chartTypeDisabledReason = 'Waiting for this insight to load'+ } else if (columns.length === 0) {+ chartTypeDisabledReason = 'This insight returned no columns to visualize'+ }+ }++ return (+ <div className="pb-2 px-2">+ <TableDisplay+ dataAttr="dashboard-insight-visualization-picker"+ disabledReason={chartTypeDisabledReason}+ disabledReasonFor={disabledReasonFor}+ fullWidth+ loading={saving}+ />+ </div>+ )+}++interface DashboardSqlVisualizationProps {+ query: DataVisualizationNode+ cachedResults: AnyResponseType+ variablesOverride?: Record<string, HogQLVariable> | null+}++export function DashboardSqlChartType({+ query,+ cachedResults,+ variablesOverride,+ persistChartType,+ disabledReason,+ loading,+ saving,+}: DashboardSqlVisualizationProps & {+ persistChartType: (display: ChartDisplayType) => void+ disabledReason?: string+ loading?: boolean+ saving?: boolean+}): JSX.Element {+ const persistQuery = useCallback(+ (nextQuery: DataVisualizationNode): void =>+ persistChartType(nextQuery.display ?? ChartDisplayType.ActionsTable),+ [persistChartType]+ )++ return (+ <DashboardSqlVisualizationLogic+ query={query}+ cachedResults={cachedResults}+ variablesOverride={variablesOverride}+ persistQuery={persistQuery}+ >+ <DashboardSqlChartTypeControl disabledReason={disabledReason} loading={loading} saving={saving} />+ </DashboardSqlVisualizationLogic>+ )+}++export function DashboardSqlDisplayOptions({+ query,+ cachedResults,+ variablesOverride,+ persistDisplayOptions,+ disabled,+}: DashboardSqlVisualizationProps & {+ persistDisplayOptions: (query: DataVisualizationNode) => void+ disabled?: boolean+}): JSX.Element {+ const inertProps = disabled ? { inert: '' } : {}++ return (+ <DashboardSqlVisualizationLogic+ query={query}+ cachedResults={cachedResults}+ variablesOverride={variablesOverride}+ persistQuery={persistDisplayOptions}+ >+ <div+ {...inertProps}+ className={`DashboardSqlDisplayOptions w-80 max-h-96 overflow-y-auto ${+ disabled ? 'pointer-events-none opacity-50' : ''+ }`}+ aria-disabled={disabled}+ >+ <DisplayTab />+ </div>+ </DashboardSqlVisualizationLogic>+ )+}diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsxindex 29d7df9cb53c..f067401b1219 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx@@ -47,7 +47,7 @@ import { dashboardsModel } from '~/models/dashboardsModel'import { insightsModel } from '~/models/insightsModel'import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'import { Node, ProductKey } from '~/queries/schema/schema-general'-import { isDataVisualizationNode } from '~/queries/utils'+import { isDataVisualizationNode, isDataVisualizationNodeWithHogQLQuery } from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -69,6 +69,8 @@ import type { AlertType } from 'products/alerts/frontend/types'import { ManageAlertsModal } from 'products/alerts/frontend/views/ManageAlertsModal'import { DashboardInsightDisplayOptions } from './DashboardInsightDisplayOptions'+import { useDashboardVisualizationOptions } from './dashboardVisualizationOptions'+import type { DashboardSqlVisualizationPersistence } from './dashboardVisualizationOptions'import { dashboardWidgetMenusLogic } from './dashboardWidgetMenusLogic'import { DashboardWidgetPlacementMenus } from './DashboardWidgetPlacementMenus'import { InsightCardProps } from './InsightCard'@@ -157,7 +159,10 @@ export function InsightMeta({}const { insightFeedback } = useValues(insightLogic(insightLogicProps))const { setInsightFeedback } = useActions(insightLogic(insightLogicProps))- const { exportContext, insightData, query } = useValues(insightDataLogic(insightLogicProps))+ const { exportContext, insightData, query, savingSqlVisualization, sqlVisualizationVersion } = useValues(+ insightDataLogic(insightLogicProps)+ )+ const { persistSqlVisualization } = useActions(insightDataLogic(insightLogicProps))const [isManageAlertsModalOpen, setIsManageAlertsModalOpen] = useState(false)const { loadAlerts: loadDeferredInsightAlerts } = useActions(insightAlertsLogic({@@ -189,7 +194,7 @@ export function InsightMeta({placement === DashboardPlacement.Dashboard ||placement === DashboardPlacement.Public ||placement === DashboardPlacement.Builtin- const isSqlInsight = isDataVisualizationNode(insight.query)+ const isSqlInsight = isDataVisualizationNodeWithHogQLQuery(insight.query)const showCompactHeading = !showCompactTile || !isSqlInsightconst ignoresDashboardFilters = !!tileFiltersOverride?.ignoreDashboardFilters@@ -240,9 +245,26 @@ export function InsightMeta({const canCreateAnomalyAlertForInsight = areAnomalyAlertsSupportedForInsight(query)const showDisplayOptionsMenu = isUsedAsDashboardTile && canEditInsight && !!persistDisplayOptions- // Hoist the hook out of the More overlay so kea logics it mounts don't do so lazily inside a+ // Hoist the hooks out of the More overlay so kea logics they mount don't do so lazily inside a// portal, which cascades into closing the dropdown before the user can interact with it.const { items: displayOptionItems } = useInsightDisplayOptions()+ const sqlVisualizationPersistence: DashboardSqlVisualizationPersistence | undefined = persistDisplayOptions+ ? {+ saving: savingSqlVisualization,+ version: sqlVisualizationVersion,+ persistChartType: (display) => persistSqlVisualization({ type: 'chart-type', display }),+ persistDisplayOptions: (sqlQuery) =>+ persistSqlVisualization({ type: 'display-options', query: sqlQuery }),+ }+ : undefined+ const visualizationItems = useDashboardVisualizationOptions({+ query,+ insightData,+ variablesOverride,+ loading: loading || loadingQueued,+ persistence: sqlVisualizationPersistence,+ })+ const displayMenuItems = [...visualizationItems, ...displayOptionItems]const hasTileStyleActions = !!(showCompactTile && toggleShowDescription && insight.description) || !!updateColorconst canShowCopyToDashboardTile = showCompactTile && !!copyToDashboard && canViewInsight@@ -513,7 +535,7 @@ export function InsightMeta({Alerts</LemonButton>) : null}- {showDisplayOptionsMenu && <DashboardInsightDisplayOptions items={displayOptionItems} />}+ {showDisplayOptionsMenu && <DashboardInsightDisplayOptions items={displayMenuItems} />}{canShowCopyToDashboardTile && !canEditDashboard && (<>diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.tsnew file mode 100644index 000000000000..fbe78c63f261--- /dev/null+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts@@ -0,0 +1,336 @@+import '@testing-library/jest-dom'++import { cleanup, render, renderHook, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { LemonMenuItems, LemonMenuSection } from 'lib/lemon-ui/LemonMenu'++import { DataVisualizationNode, InsightVizNode, Node, NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { ChartDisplayType } from '~/types'++import { sqlQueryForVisualizationPicker, useDashboardVisualizationOptions } from './dashboardVisualizationOptions'++type DashboardVisualizationOptionsProps = Parameters<typeof useDashboardVisualizationOptions>[0]++function displayOptionsElement(items: LemonMenuItems): JSX.Element {+ const section = items.find((item): item is LemonMenuSection => !!item && 'title' in item && item.key === 'display')+ expect(section).not.toBeUndefined()++ const item = section?.items[0]+ expect(item && typeof item.label).toBe('function')++ return (item as { label: () => JSX.Element }).label()+}++function chartTypeElement(items: LemonMenuItems): JSX.Element {+ const section = items.find(+ (item): item is LemonMenuSection => !!item && 'title' in item && item.title === 'Chart type'+ )+ expect(section).not.toBeUndefined()++ const item = section?.items[0]+ expect(item && typeof item.label).toBe('function')++ return (item as { label: () => JSX.Element }).label()+}++describe('dashboardVisualizationOptions', () => {+ const sqlQuery = {+ kind: NodeKind.DataVisualizationNode,+ source: { kind: NodeKind.HogQLQuery, query: 'select 1' },+ } as DataVisualizationNode++ const trendsQuery = {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.TrendsQuery, series: [] },+ } as unknown as InsightVizNode++ afterEach(() => {+ cleanup()+ })++ describe('sqlQueryForVisualizationPicker', () => {+ it.each([+ { label: 'SQL insight gets the picker', query: sqlQuery as Node, canPersist: true, expected: sqlQuery },+ {+ label: 'a trends insight gets nothing, since its chart type carries query side effects',+ query: trendsQuery as Node,+ canPersist: true,+ expected: null,+ },+ {+ label: 'a non-SQL data visualization gets nothing',+ query: {+ kind: NodeKind.DataVisualizationNode,+ source: { kind: NodeKind.EventsQuery },+ } as unknown as DataVisualizationNode,+ canPersist: true,+ expected: null,+ },+ {+ label: 'no picker when the change cannot be saved, so a viewer never gets a control that no-ops',+ query: sqlQuery as Node,+ canPersist: false,+ expected: null,+ },+ { label: 'no picker without a query', query: null, canPersist: true, expected: null },+ ])('$label', ({ query, canPersist, expected }) => {+ expect(sqlQueryForVisualizationPicker(query, canPersist)).toBe(expected)+ })+ })++ describe('SQL display controls', () => {+ const insightData = {+ columns: ['day', 'total'],+ types: [+ ['day', 'DateTime'],+ ['total', 'UInt64'],+ ],+ result: [+ ['2026-08-30', 12],+ ['2026-08-31', 15],+ ],+ }++ const lineQuery = {+ ...sqlQuery,+ display: ChartDisplayType.ActionsLineGraph,+ chartSettings: { xAxis: { column: 'day' }, yAxis: [{ column: 'total' }] },+ } as DataVisualizationNode++ const baseProps: DashboardVisualizationOptionsProps = {+ query: lineQuery,+ insightData,+ persistence: {+ saving: null,+ version: 0,+ persistChartType: jest.fn(),+ persistDisplayOptions: jest.fn(),+ },+ }++ beforeEach(() => {+ initKeaTests()+ })++ it('persists the chart type selected through the editor control', async () => {+ const persistChartType = jest.fn()+ const { result } = renderHook(() =>+ useDashboardVisualizationOptions({+ ...baseProps,+ persistence: { ...baseProps.persistence!, persistChartType },+ })+ )+ const { container } = render(chartTypeElement(result.current))++ await userEvent.click(+ container.querySelector('[data-attr="dashboard-insight-visualization-picker"]') as HTMLElement+ )+ const matches = screen.getAllByText('Bar chart')+ await userEvent.click(matches[matches.length - 1])++ expect(persistChartType).toHaveBeenCalledWith(ChartDisplayType.ActionsBar)+ })++ it('restores the saved chart type after a failed save', async () => {+ const { result, rerender } = renderHook(+ (props: DashboardVisualizationOptionsProps) => useDashboardVisualizationOptions(props),+ { initialProps: baseProps }+ )+ const view = render(chartTypeElement(result.current))++ await userEvent.click(+ view.container.querySelector('[data-attr="dashboard-insight-visualization-picker"]') as HTMLElement+ )+ const matches = screen.getAllByText('Bar chart')+ await userEvent.click(matches[matches.length - 1])+ expect(+ view.container.querySelector('[data-attr="dashboard-insight-visualization-picker"]')+ ).toHaveTextContent('Bar chart')++ rerender({+ ...baseProps,+ persistence: { ...baseProps.persistence!, version: 1 },+ })+ view.rerender(chartTypeElement(result.current))++ expect(+ view.container.querySelector('[data-attr="dashboard-insight-visualization-picker"]')+ ).toHaveTextContent('Line chart')+ })++ it('reloads the available controls when the SQL chart type changes', async () => {+ const { result, rerender } = renderHook(+ (props: DashboardVisualizationOptionsProps) => useDashboardVisualizationOptions(props),+ { initialProps: baseProps }+ )+ const view = render(displayOptionsElement(result.current))++ expect(await screen.findByText('Right Y-axis')).toBeInTheDocument()+ expect(screen.getByText('Goals')).toBeInTheDocument()++ rerender({+ ...baseProps,+ query: {+ ...lineQuery,+ display: ChartDisplayType.ActionsPie,+ } as DataVisualizationNode,+ })+ view.rerender(displayOptionsElement(result.current))++ expect(await screen.findByText('Show on slices')).toBeInTheDocument()+ expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()+ expect(screen.queryByText('Goals')).not.toBeInTheDocument()+ })++ it('routes display setting changes through SQL-safe persistence', async () => {+ const persistSqlDisplayOptions = jest.fn()+ const { result } = renderHook(() =>+ useDashboardVisualizationOptions({+ ...baseProps,+ persistence: { ...baseProps.persistence!, persistDisplayOptions: persistSqlDisplayOptions },+ })+ )+ render(displayOptionsElement(result.current))++ const showLegend = await screen.findByLabelText('Show legend')+ expect(persistSqlDisplayOptions).not.toHaveBeenCalled()++ await userEvent.click(showLegend)++ await waitFor(() => {+ expect(persistSqlDisplayOptions).toHaveBeenCalledWith(+ expect.objectContaining({+ chartSettings: expect.objectContaining({ showLegend: true }),+ })+ )+ })+ })++ it('waits for result columns before mounting display controls', async () => {+ const { result, rerender } = renderHook(+ (props: DashboardVisualizationOptionsProps) => useDashboardVisualizationOptions(props),+ {+ initialProps: {+ ...baseProps,+ insightData: {},+ loading: true,+ },+ }+ )+ const view = render(displayOptionsElement(result.current))++ expect(screen.getByRole('status')).toHaveTextContent('Loading display options')+ expect(screen.queryByLabelText('Show legend')).not.toBeInTheDocument()++ rerender({ ...baseProps, loading: false })+ view.rerender(displayOptionsElement(result.current))++ expect(await screen.findByLabelText('Show legend')).toBeInTheDocument()+ })++ it('combines rapid setting changes across saving-state rerenders', async () => {+ const persistSqlDisplayOptions = jest.fn()+ const { result, rerender } = renderHook(+ (props: DashboardVisualizationOptionsProps) => useDashboardVisualizationOptions(props),+ {+ initialProps: {+ ...baseProps,+ persistence: { ...baseProps.persistence!, persistDisplayOptions: persistSqlDisplayOptions },+ },+ }+ )+ const view = render(displayOptionsElement(result.current))++ await userEvent.click(await screen.findByLabelText('Show legend'))+ const displayLabel = (+ result.current.find((item) => item && 'key' in item && item.key === 'display') as LemonMenuSection+ ).items[0]+ rerender({+ ...baseProps,+ persistence: {+ ...baseProps.persistence!,+ saving: 'display-options',+ persistDisplayOptions: persistSqlDisplayOptions,+ },+ })+ const rerenderedDisplayLabel = (+ result.current.find((item) => item && 'key' in item && item.key === 'display') as LemonMenuSection+ ).items[0]+ expect(+ rerenderedDisplayLabel && 'label' in rerenderedDisplayLabel ? rerenderedDisplayLabel.label : null+ ).toBe(displayLabel && 'label' in displayLabel ? displayLabel.label : null)+ view.rerender(displayOptionsElement(result.current))+ expect(screen.getByLabelText('Show legend')).toBeChecked()+ await userEvent.click(screen.getByLabelText('Show annotations'))++ expect(persistSqlDisplayOptions).toHaveBeenLastCalledWith(+ expect.objectContaining({+ chartSettings: expect.objectContaining({ showLegend: true, showAnnotations: true }),+ })+ )+ })++ it('shows when SQL visualization settings are being saved', () => {+ const { result } = renderHook(() =>+ useDashboardVisualizationOptions({+ ...baseProps,+ persistence: { ...baseProps.persistence!, saving: 'display-options' },+ })+ )++ render(+ (result.current.find((item) => item && 'key' in item && item.key === 'display') as LemonMenuSection)+ .title as JSX.Element+ )++ expect(screen.getByRole('status')).toHaveTextContent('Saving')+ })++ it('keeps display controls interactive while display options are being saved', () => {+ const { result } = renderHook(() =>+ useDashboardVisualizationOptions({+ ...baseProps,+ persistence: { ...baseProps.persistence!, saving: 'display-options' },+ })+ )++ const { container } = render(displayOptionsElement(result.current))++ expect(container.firstChild).not.toHaveAttribute('inert')+ })++ it('makes display controls inert while the chart type is being saved', () => {+ const { result } = renderHook(() =>+ useDashboardVisualizationOptions({+ ...baseProps,+ persistence: { ...baseProps.persistence!, saving: 'chart-type' },+ })+ )++ const { container } = render(displayOptionsElement(result.current))++ expect(container.firstChild).toHaveAttribute('inert')+ })++ it('restores saved display settings after a failed save', async () => {+ const { result, rerender } = renderHook(+ (props: DashboardVisualizationOptionsProps) => useDashboardVisualizationOptions(props),+ { initialProps: baseProps }+ )+ const view = render(displayOptionsElement(result.current))++ await userEvent.click(await screen.findByLabelText('Show legend'))+ expect(screen.getByLabelText('Show legend')).toBeChecked()++ rerender({+ ...baseProps,+ persistence: { ...baseProps.persistence!, version: 1 },+ })+ view.rerender(displayOptionsElement(result.current))++ expect(await screen.findByLabelText('Show legend')).not.toBeChecked()+ })+ })+})diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.tsx b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.tsxnew file mode 100644index 000000000000..4f5b315d3638--- /dev/null+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.tsx@@ -0,0 +1,131 @@+import { useCallback, useMemo, useRef } from 'react'++import { Spinner } from '@posthog/lemon-ui'++import { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'++import { isDisplayTabSupported } from '~/queries/nodes/DataVisualization/Components/SideBar'+import { DataVisualizationNode, HogQLVariable, Node } from '~/queries/schema/schema-general'+import { isDataVisualizationNodeWithHogQLQuery } from '~/queries/utils'+import { ChartDisplayType } from '~/types'++import { DashboardSqlChartType, DashboardSqlDisplayOptions } from './DashboardSqlDisplayOptions'++export interface DashboardSqlVisualizationPersistence {+ saving: 'chart-type' | 'display-options' | null+ version: number+ persistChartType: (display: ChartDisplayType) => void+ persistDisplayOptions: (query: DataVisualizationNode) => void+}++export function sqlQueryForVisualizationPicker(query: Node | null, canPersist: boolean): DataVisualizationNode | null {+ return canPersist && query && isDataVisualizationNodeWithHogQLQuery(query) ? query : null+}++export function useDashboardVisualizationOptions({+ query,+ insightData,+ variablesOverride,+ loading,+ persistence,+}: {+ query: Node | null+ insightData: Record<string, any>+ variablesOverride?: Record<string, HogQLVariable> | null+ loading?: boolean+ persistence?: DashboardSqlVisualizationPersistence+}): LemonMenuItems {+ const sqlQuery = sqlQueryForVisualizationPicker(query, !!persistence)+ const overriddenVariable = Object.keys(sqlQuery?.source.variables ?? {}).find((key) => variablesOverride?.[key])++ const pickerProps = {+ query: sqlQuery,+ cachedResults: insightData,+ variablesOverride,+ loading,+ saving: persistence?.saving === 'chart-type',+ version: persistence?.version,+ overriddenVariable,+ persistChartType: persistence?.persistChartType,+ }+ const pickerPropsRef = useRef(pickerProps)+ pickerPropsRef.current = pickerProps+ const renderPicker = useCallback((): JSX.Element => {+ const props = pickerPropsRef.current+ return (+ <DashboardSqlChartType+ key={props.version}+ query={props.query!}+ cachedResults={props.cachedResults}+ variablesOverride={props.variablesOverride}+ loading={props.loading}+ saving={props.saving}+ disabledReason={+ props.overriddenVariable+ ? 'This dashboard overrides a variable this insight uses. Open the insight to change its chart type.'+ : undefined+ }+ persistChartType={props.persistChartType!}+ />+ )+ }, [])++ const displayOptionsProps = {+ query: sqlQuery,+ cachedResults: insightData,+ variablesOverride,+ loading,+ persistence,+ }+ const displayOptionsPropsRef = useRef(displayOptionsProps)+ displayOptionsPropsRef.current = displayOptionsProps+ const renderDisplayOptions = useCallback((): JSX.Element => {+ const props = displayOptionsPropsRef.current+ if (props.loading) {+ return (+ <div className="flex min-h-20 w-80 items-center justify-center gap-2 text-muted" role="status">+ <Spinner /> Loading display options+ </div>+ )+ }+ return (+ <DashboardSqlDisplayOptions+ key={props.persistence!.version}+ query={props.query!}+ cachedResults={props.cachedResults}+ variablesOverride={props.variablesOverride}+ persistDisplayOptions={props.persistence!.persistDisplayOptions}+ disabled={props.persistence!.saving === 'chart-type'}+ />+ )+ }, [])++ return useMemo<LemonMenuItems>(() => {+ if (!sqlQuery || !persistence) {+ return []+ }++ return [+ {+ title: 'Chart type',+ items: [{ label: renderPicker }],+ },+ isDisplayTabSupported(sqlQuery.display ?? ChartDisplayType.ActionsTable)+ ? {+ key: 'display',+ title: (+ <h5 className="mx-2 my-1 flex items-center justify-between gap-2">+ Display+ {persistence.saving ? (+ <span className="flex items-center gap-1 font-normal text-muted" role="status">+ <Spinner /> Saving+ </span>+ ) : null}+ </h5>+ ),+ items: [{ label: renderDisplayOptions }],+ }+ : false,+ ]+ }, [sqlQuery, persistence, renderPicker, renderDisplayOptions])+}diff --git a/frontend/src/lib/components/Cards/InsightCard/sqlVisualizationSupport.test.ts b/frontend/src/lib/components/Cards/InsightCard/sqlVisualizationSupport.test.tsnew file mode 100644index 000000000000..ab8d68320d2e--- /dev/null+++ b/frontend/src/lib/components/Cards/InsightCard/sqlVisualizationSupport.test.ts@@ -0,0 +1,158 @@+import { getTableDisplayOptions } from '~/queries/nodes/DataVisualization/Components/TableDisplay'+import {+ applyVisualizationType,+ columnsFromResponse,+ getAutoVisualizationType,+} from '~/queries/nodes/DataVisualization/dataVisualizationLogic'+import { sqlVisualizationDisabledReason } from '~/queries/nodes/DataVisualization/sqlVisualizationSupport'+import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++describe('dashboard SQL visualization support', () => {+ const responses = {+ 'date and numeric': {+ columns: ['day', 'total'],+ types: [+ ['day', 'DateTime'],+ ['total', 'UInt64'],+ ],+ result: [+ ['2026-01-01', 1],+ ['2026-01-02', 2],+ ],+ },+ 'two strings and a numeric, which Auto resolves to a 2d heatmap': {+ columns: ['country', 'browser', 'hits'],+ types: [+ ['country', 'String'],+ ['browser', 'String'],+ ['hits', 'UInt64'],+ ],+ result: [['NL', 'Firefox', 3]],+ },+ 'all numeric, which the editor plots by promoting the first column to the x axis': {+ columns: ['users', 'events'],+ types: [+ ['users', 'UInt64'],+ ['events', 'UInt64'],+ ],+ result: [[1, 2]],+ },+ 'all string, so nothing is left to plot': {+ columns: ['country', 'browser'],+ types: [+ ['country', 'String'],+ ['browser', 'String'],+ ],+ result: [['NL', 'Firefox']],+ },+ 'a single numeric column': {+ columns: ['total'],+ types: [['total', 'UInt64']],+ result: [[7]],+ },+ }++ const baseQuery = {+ kind: NodeKind.DataVisualizationNode,+ source: { kind: NodeKind.HogQLQuery, query: 'select 1' },+ } as DataVisualizationNode++ it.each(Object.entries(responses))(+ 'every type the card leaves enabled saves a query it can draw: %s',+ (_label, response) => {+ const columns = columnsFromResponse(response)+ const autoVisualizationType = getAutoVisualizationType(columns, response.result.length)+ const numericalColumns = columns.filter((column) => column.type.isNumerical)++ const options = getTableDisplayOptions(columns, numericalColumns, autoVisualizationType, (displayType) =>+ sqlVisualizationDisabledReason(+ displayType,+ baseQuery,+ columns,+ response.result.length,+ autoVisualizationType+ )+ )++ const enabled = options+ .flatMap((group: any) => (Array.isArray(group.options) ? group.options : []))+ .filter((option: any) => !option.disabledReason)+ .map((option: any) => option.value as ChartDisplayType)++ expect(enabled.length).toBeGreaterThan(0)++ for (const displayType of enabled) {+ const saved = applyVisualizationType(baseQuery, displayType, columns, response.result.length)+ const resolved =+ displayType === ChartDisplayType.Auto ? autoVisualizationType : (displayType as ChartDisplayType)++ const needsAxes = ![ChartDisplayType.ActionsTable, ChartDisplayType.BoldNumber].includes(resolved)+ if (!needsAxes) {+ continue+ }++ expect(saved.chartSettings?.xAxis?.column).toEqual(expect.any(String))+ expect(saved.chartSettings?.yAxis?.length ?? 0).toBeGreaterThan(0)+ }+ }+ )++ it('does not offer Auto when it resolves to a type the card cannot set up', () => {+ const response = responses['two strings and a numeric, which Auto resolves to a 2d heatmap']+ const columns = columnsFromResponse(response)+ const autoVisualizationType = getAutoVisualizationType(columns, response.result.length)++ expect(autoVisualizationType).toEqual(ChartDisplayType.TwoDimensionalHeatmap)+ expect(+ sqlVisualizationDisabledReason(+ ChartDisplayType.Auto,+ baseQuery,+ columns,+ response.result.length,+ autoVisualizationType+ )+ ).toContain('Open the insight')+ })++ it('does not treat stale saved axes as making a chart type available', () => {+ const response = responses['all string, so nothing is left to plot']+ const columns = columnsFromResponse(response)+ const autoVisualizationType = getAutoVisualizationType(columns, response.result.length)+ const staleAxes = {+ ...baseQuery,+ chartSettings: { xAxis: { column: 'country' }, yAxis: [{ column: 'browser' }] },+ } as DataVisualizationNode++ for (const candidate of [baseQuery, staleAxes]) {+ expect(+ sqlVisualizationDisabledReason(+ ChartDisplayType.ActionsBar,+ candidate,+ columns,+ response.result.length,+ autoVisualizationType+ )+ ).toEqual('This insight has no numeric column to plot')+ }+ })++ it('preserves saved axes while response columns are unavailable', () => {+ const query = {+ ...baseQuery,+ chartSettings: {+ xAxis: { column: 'day' },+ yAxis: [+ {+ column: 'total',+ settings: { formatting: { prefix: '$', suffix: '' } },+ },+ ],+ },+ } as DataVisualizationNode++ expect(applyVisualizationType(query, ChartDisplayType.ActionsBar, [], 0).chartSettings).toEqual(+ query.chartSettings+ )+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/SideBar.tsx b/frontend/src/queries/nodes/DataVisualization/Components/SideBar.tsxindex 1efc00f7ec17..b7fb636708dd 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/SideBar.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/SideBar.tsx@@ -16,6 +16,11 @@ type TabContent = {shouldShow: (displayType: ChartDisplayType) => boolean}+export const isDisplayTabSupported = (displayType: ChartDisplayType): boolean =>+ displayType !== ChartDisplayType.ActionsTable &&+ displayType !== ChartDisplayType.BoldNumber &&+ displayType !== ChartDisplayType.TwoDimensionalHeatmap+const TABS_TO_CONTENT: Record<SideBarTab, TabContent> = {[SideBarTab.Series]: {label: 'Series',@@ -30,10 +35,7 @@ const TABS_TO_CONTENT: Record<SideBarTab, TabContent> = {[SideBarTab.Display]: {label: 'Display',content: <DisplayTab />,- shouldShow: (displayType: ChartDisplayType): boolean =>- displayType !== ChartDisplayType.ActionsTable &&- displayType !== ChartDisplayType.BoldNumber &&- displayType !== ChartDisplayType.TwoDimensionalHeatmap,+ shouldShow: isDisplayTabSupported,},}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsxindex 897f64106198..922f49a6b003 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx@@ -9,60 +9,59 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ChartDisplayType } from '~/types'-import { dataVisualizationLogic } from '../dataVisualizationLogic'+import { Column, dataVisualizationLogic } from '../dataVisualizationLogic'-interface TableDisplayProps extends Pick<LemonSelectProps<ChartDisplayType>, 'disabledReason'> {}--export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element => {- const { setVisualizationType } = useActions(dataVisualizationLogic)- const { autoVisualizationType, columns, numericalColumns, visualizationType } = useValues(dataVisualizationLogic)- const { featureFlags } = useValues(featureFlagLogic)+const DISPLAY_TYPE_LABELS: Record<ChartDisplayType, string> = {+ [ChartDisplayType.Auto]: 'Auto',+ [ChartDisplayType.ActionsLineGraph]: 'Line chart',+ [ChartDisplayType.ActionsBar]: 'Bar chart',+ [ChartDisplayType.ActionsUnstackedBar]: 'Unstacked bar chart',+ [ChartDisplayType.ActionsStackedBar]: 'Stacked bar chart',+ [ChartDisplayType.ActionsAreaGraph]: 'Area chart',+ [ChartDisplayType.ActionsLineGraphCumulative]: 'Cumulative line chart',+ [ChartDisplayType.BoldNumber]: 'Big number',+ [ChartDisplayType.Metric]: 'Metric',+ [ChartDisplayType.ActionsPie]: 'Pie chart',+ [ChartDisplayType.ActionsDonut]: 'Donut chart',+ [ChartDisplayType.ActionsBarValue]: 'Value chart',+ [ChartDisplayType.ActionsTable]: 'Table',+ [ChartDisplayType.WorldMap]: 'World map',+ [ChartDisplayType.CalendarHeatmap]: 'Calendar heatmap',+ [ChartDisplayType.TwoDimensionalHeatmap]: '2d heatmap',+ [ChartDisplayType.BoxPlot]: 'Box plot',+ [ChartDisplayType.SlopeGraph]: 'Slope graph',+ [ChartDisplayType.ScatterPlot]: 'Scatter plot',+}- const canDisplayContinuousChart = columns.length > 1 && numericalColumns.length > 0- // Both scatter axes are numeric measures, so one numeric column can't fill both.- const canDisplayScatterPlot = numericalColumns.length > 1+export function renderDisplayTypeLabel(displayType: ChartDisplayType, autoVisualizationType: ChartDisplayType): string {+ const selectedLabel = DISPLAY_TYPE_LABELS[displayType] ?? displayType- const displayTypeLabels: Record<ChartDisplayType, string> = {- [ChartDisplayType.Auto]: 'Auto',- [ChartDisplayType.ActionsLineGraph]: 'Line chart',- [ChartDisplayType.ActionsBar]: 'Bar chart',- [ChartDisplayType.ActionsUnstackedBar]: 'Unstacked bar chart',- [ChartDisplayType.ActionsStackedBar]: 'Stacked bar chart',- [ChartDisplayType.ActionsAreaGraph]: 'Area chart',- [ChartDisplayType.ActionsLineGraphCumulative]: 'Cumulative line chart',- [ChartDisplayType.BoldNumber]: 'Big number',- [ChartDisplayType.Metric]: 'Metric',- [ChartDisplayType.ActionsPie]: 'Pie chart',- [ChartDisplayType.ActionsDonut]: 'Donut chart',- [ChartDisplayType.ActionsBarValue]: 'Value chart',- [ChartDisplayType.ActionsTable]: 'Table',- [ChartDisplayType.WorldMap]: 'World map',- [ChartDisplayType.CalendarHeatmap]: 'Calendar heatmap',- [ChartDisplayType.TwoDimensionalHeatmap]: '2d heatmap',- [ChartDisplayType.BoxPlot]: 'Box plot',- [ChartDisplayType.SlopeGraph]: 'Slope graph',- [ChartDisplayType.ScatterPlot]: 'Scatter plot',+ if (displayType !== ChartDisplayType.Auto) {+ return selectedLabel}- const renderDisplayTypeLabel = (displayType: ChartDisplayType): string => {- const selectedLabel = displayTypeLabels[displayType] ?? displayType-- if (displayType !== ChartDisplayType.Auto) {- return selectedLabel- }+ const resolvedLabel = DISPLAY_TYPE_LABELS[autoVisualizationType] ?? autoVisualizationType+ return `Auto (${resolvedLabel})`+}- const resolvedLabel = displayTypeLabels[autoVisualizationType] ?? autoVisualizationType- return `Auto (${resolvedLabel})`- }+export function getTableDisplayOptions(+ columns: Column[],+ numericalColumns: Column[],+ autoVisualizationType: ChartDisplayType,+ disabledReasonFor?: (displayType: ChartDisplayType) => string | undefined,+ showBoxPlot = false+): LemonSelectOptions<ChartDisplayType> {+ const canDisplayContinuousChart = columns.length > 1 && numericalColumns.length > 0+ const canDisplayScatterPlot = numericalColumns.length > 1- const options: LemonSelectOptions<ChartDisplayType> = [+ const groups: LemonSelectOptions<ChartDisplayType> = [{title: 'Auto',options: [{value: ChartDisplayType.Auto,icon: <IconTrends />,- label: renderDisplayTypeLabel(ChartDisplayType.Auto),+ label: renderDisplayTypeLabel(ChartDisplayType.Auto, autoVisualizationType),},],},@@ -77,7 +76,7 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element{value: ChartDisplayType.BoldNumber,icon: <Icon123 />,- label: 'Big Number',+ label: 'Big number',},],},@@ -123,7 +122,7 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element? 'Requires at least two numeric columns, one for each axis': undefined,},- ...(featureFlags[FEATURE_FLAGS.SQL_BOX_PLOT_INSIGHT]+ ...(showBoxPlot? [{value: ChartDisplayType.BoxPlot,@@ -143,20 +142,59 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element},]+ if (!disabledReasonFor) {+ return groups+ }++ return groups.map((group) => ({+ ...group,+ options: group.options.map((option) =>+ 'value' in option+ ? { ...option, disabledReason: option.disabledReason ?? disabledReasonFor(option.value) }+ : option+ ),+ }))+}++interface TableDisplayProps extends Pick<+ LemonSelectProps<ChartDisplayType>,+ 'disabledReason' | 'fullWidth' | 'loading'+> {+ dataAttr?: string+ disabledReasonFor?: (displayType: ChartDisplayType) => string | undefined+}++export const TableDisplay = ({+ dataAttr = 'chart-filter',+ disabledReason,+ disabledReasonFor,+ fullWidth,+ loading,+}: TableDisplayProps): JSX.Element => {+ const { setVisualizationType } = useActions(dataVisualizationLogic)+ const { autoVisualizationType, columns, numericalColumns, visualizationType } = useValues(dataVisualizationLogic)+ const { featureFlags } = useValues(featureFlagLogic)+return (<LemonSelectdisabledReason={disabledReason}- value={visualizationType}- renderButtonContent={() => renderDisplayTypeLabel(visualizationType)}- onChange={(value) => {- setVisualizationType(value)- }}+ dropdownMatchSelectWidth={false}dropdownPlacement="bottom-end"+ fullWidth={fullWidth}+ loading={loading}+ onChange={setVisualizationType}optionTooltipPlacement="left"- dropdownMatchSelectWidth={false}- data-attr="chart-filter"- options={options}+ options={getTableDisplayOptions(+ columns,+ numericalColumns,+ autoVisualizationType,+ disabledReasonFor,+ !!featureFlags[FEATURE_FLAGS.SQL_BOX_PLOT_INSIGHT]+ )}+ renderButtonContent={() => renderDisplayTypeLabel(visualizationType, autoVisualizationType)}size="small"+ value={visualizationType}+ data-attr={dataAttr}/>)}diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.tsindex aeb1a333c80d..b3e835d0a1d9 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts@@ -136,6 +136,30 @@ describe('dataVisualizationLogic', () => {})})+ it('initializes axes when columns load after selecting a visualization type', async () => {+ logic.actions.setVisualizationType(ChartDisplayType.ActionsLineGraph)++ await expectLogic(logic).toMatchValues({+ selectedXAxis: null,+ selectedYAxis: null,+ })++ dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({+ results: [['signed_up', 'Safari', 11]],+ columns: ['event', 'browser', 'total_count'],+ types: [+ ['event', 'String'],+ ['browser', 'Nullable(String)'],+ ['total_count', 'UInt64'],+ ],+ })++ await expectLogic(logic).toMatchValues({+ selectedXAxis: 'event',+ selectedYAxis: [expect.objectContaining({ name: 'total_count' })],+ })+ })+it('auto-maps box plot columns when the chart is selected', async () => {dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({columns: ['bucket', 'series', 'min', 'p25', 'median', 'mean', 'p75', 'max'],@@ -500,13 +524,13 @@ describe('dataVisualizationLogic', () => {await expectLogic(logic).toMatchValues({visualizationType: ChartDisplayType.Auto,effectiveVisualizationType: ChartDisplayType.TwoDimensionalHeatmap,- chartSettings: {+ chartSettings: expect.objectContaining({heatmap: {xAxisColumn: 'region',yAxisColumn: 'segment',valueColumn: 'count',},- },+ }),})})diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.tsindex ed05870a686f..12cc8a5b5f6a 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts@@ -276,6 +276,47 @@ const isNumericalType = (type: ColumnScalar): boolean => {return false}+const columnsFromResponseFields = (columns: string[] = [], types: string[][] = []): Column[] => {+ return columns.map((column, index) => {+ const type = types[index]?.[1]+ const friendlyClickhouseTypeName = toFriendlyClickhouseTypeName(type)++ return {+ name: column,+ type: {+ name: friendlyClickhouseTypeName,+ isNumerical: isNumericalType(friendlyClickhouseTypeName),+ },+ label: `${column} - ${type}`,+ dataIndex: index,+ }+ })+}++export const columnsFromResponse = (response: AnyResponseType | null): Column[] => {+ if (!response) {+ return []+ }++ return columnsFromResponseFields(+ 'columns' in response && Array.isArray(response.columns) ? response.columns : [],+ 'types' in response && Array.isArray(response.types) ? response.types : []+ )+}++const deriveDefaultAxes = (columns: Column[]): { xAxis: string | null; yAxis: string[] } => {+ const dateColumn = columns.find((column) => column.type.name.indexOf('DATE') !== -1)+ const numericalColumns = columns.filter((column) => column.type.isNumerical)+ const yAxis = numericalColumns.map((column) => column.name)++ if (dateColumn) {+ return { xAxis: dateColumn.name, yAxis }+ }++ const claimed = new Set(yAxis)+ return { xAxis: columns.find((column) => !claimed.has(column.name))?.name ?? null, yAxis }+}+const resolveNonTimeSeriesVisualizationType = (columns: Column[]): ChartDisplayType => {const stringColumns = columns.filter((column) => column.type.name === 'STRING')const numericalColumns = columns.filter((column) => column.type.isNumerical)@@ -295,17 +336,21 @@ const resolveNonTimeSeriesVisualizationType = (columns: Column[]): ChartDisplayTreturn ChartDisplayType.ActionsTable}-const hasTimeSeriesData = (columns: Column[], response: AnyResponseType | null): boolean => {+export const rowCountFromResponse = (response: AnyResponseType | null): number => {+ const rawResults =+ response && 'results' in response ? response.results : response && 'result' in response ? response.result : []+ return Array.isArray(rawResults) ? rawResults.length : 0+}++const hasTimeSeriesData = (columns: Column[], rowCount: number): boolean => {const hasDateColumn = columns.some((column) => ['DATE', 'DATETIME'].includes(column.type.name))const hasNumericColumn = columns.some((column) => column.type.isNumerical)- const results =- response && 'results' in response ? response.results : response && 'result' in response ? response.result : []- return hasDateColumn && hasNumericColumn && results.length > 1+ return hasDateColumn && hasNumericColumn && rowCount > 1}-const getAutoVisualizationType = (columns: Column[], response: AnyResponseType | null): ChartDisplayType => {- if (hasTimeSeriesData(columns, response)) {+export const getAutoVisualizationType = (columns: Column[], rowCount: number): ChartDisplayType => {+ if (hasTimeSeriesData(columns, rowCount)) {return ChartDisplayType.ActionsLineGraph}@@ -412,7 +457,7 @@ const shouldUseFirstNumericColumnAsContinuousChartXAxis = (columns: Column[],numericalColumns: Column[],selectedXAxis: string | null,- selectedYAxis: (SelectedYAxis | null)[] | null+ selectedYAxis: (Pick<SelectedYAxis, 'name'> | null)[] | null): boolean => {if (selectedXAxis !== null || columns.length < 2 || numericalColumns.length < 2) {return false@@ -431,21 +476,12 @@ const shouldUseFirstNumericColumnAsContinuousChartXAxis = (return numericalColumns.every((column) => selectedYAxisNames.has(column.name))}-/**- * A scatter plots two measures against each other, so its x axis has to hold a numeric column.- * Returns the column that should sit on the x axis: the current one when it's already numeric,- * otherwise a numeric column to move there, preferring one that isn't already a y-series so the- * chart isn't left with nothing on either axis. Returns null only when a scatter can't be plotted- * (fewer than two numeric columns). The caller drops the chosen column from the y-series if it's- * also there, so a column never plots against itself.- */const resolveScatterXAxisColumn = (columns: Column[],numericalColumns: Column[],selectedXAxis: string | null,- selectedYAxis: (SelectedYAxis | null)[] | null+ selectedYAxis: (Pick<SelectedYAxis, 'name'> | null)[] | null): Column | null => {- // Two numeric columns at minimum — taking the only one for the x axis leaves nothing to plot.if (numericalColumns.length < 2) {return null}@@ -459,10 +495,90 @@ const resolveScatterXAxisColumn = (return numericalColumns.find((column) => !selectedYAxisNames.has(column.name)) ?? numericalColumns[0]}+export function applyVisualizationType(+ query: DataVisualizationNode,+ visualizationType: ChartDisplayType,+ columns: Column[],+ rowCount: number+): DataVisualizationNode {+ const numericalColumns = columns.filter((column) => column.type.isNumerical)+ const chartSettings: ChartSettings = { ...query.chartSettings }++ const columnNames = new Set(columns.map((column) => column.name))+ const invalidX = chartSettings.xAxis !== undefined && !columnNames.has(chartSettings.xAxis.column)+ const invalidY =+ chartSettings.yAxis?.some(+ (series) => !columns.find((column) => column.name === series.column)?.type.isNumerical+ ) ?? false++ if (columns.length > 0 && (invalidX || invalidY)) {+ chartSettings.xAxis = undefined+ chartSettings.yAxis = undefined+ }++ // An empty yAxis records that the user deleted every series, so only absent axes are seeded.+ if (chartSettings.xAxis === undefined && chartSettings.yAxis === undefined) {+ const seeded = deriveDefaultAxes(columns)+ if (seeded.yAxis.length > 0) {+ chartSettings.yAxis = seeded.yAxis.map((column) => ({ column, settings: DefaultAxisSettings() }))+ }+ if (seeded.xAxis) {+ chartSettings.xAxis = { column: seeded.xAxis }+ }+ }++ const selectedXAxis = chartSettings.xAxis?.column ?? null+ let yAxis = chartSettings.yAxis ? [...chartSettings.yAxis] : []+ const selectedYAxis = yAxis.map((series) => ({ name: series.column }))++ if (visualizationType === ChartDisplayType.ActionsPie && chartSettings.pie?.sliceContent === undefined) {+ chartSettings.pie = { ...chartSettings.pie, sliceContent: 'labels' }+ }++ if (+ [ChartDisplayType.ActionsLineGraph, ChartDisplayType.ActionsAreaGraph].includes(visualizationType) &&+ shouldUseFirstNumericColumnAsContinuousChartXAxis(columns, numericalColumns, selectedXAxis, selectedYAxis)+ ) {+ const [xAxisColumn] = numericalColumns+ chartSettings.xAxis = { column: xAxisColumn.name }+ yAxis = yAxis.filter((series) => series.column !== xAxisColumn.name)+ }++ if (visualizationType === ChartDisplayType.ScatterPlot) {+ const xAxisColumn = resolveScatterXAxisColumn(columns, numericalColumns, selectedXAxis, selectedYAxis)+ if (xAxisColumn) {+ chartSettings.xAxis = { column: xAxisColumn.name }+ yAxis = yAxis.filter((series) => series.column !== xAxisColumn.name)+ }+ }++ if (visualizationType === ChartDisplayType.BoxPlot) {+ chartSettings.boxPlot = getAutoBoxPlotSettings(columns, chartSettings.boxPlot)+ }++ const isAutoHeatmap =+ visualizationType === ChartDisplayType.Auto &&+ getAutoVisualizationType(columns, rowCount) === ChartDisplayType.TwoDimensionalHeatmap++ if (visualizationType === ChartDisplayType.TwoDimensionalHeatmap || isAutoHeatmap) {+ const heatmap = chartSettings.heatmap ?? {}+ const autoSettings = getHeatmapAutoSettings(columns, heatmap)+ if (Object.keys(autoSettings).length > 0) {+ chartSettings.heatmap = { ...heatmap, ...autoSettings }+ }+ }++ if (chartSettings.yAxis !== undefined) {+ chartSettings.yAxis = yAxis+ }++ return { ...query, display: visualizationType, chartSettings }+}+/*** Establishes the scatter x-axis invariant: a numeric column on the x axis that isn't also a- * y-series. Runs from every entry path a scatter can arrive through — the type being picked, the- * query's columns changing, and a persisted/assistant-created insight loading — so the chart never+ * y-series. Runs from every entry path a scatter can arrive through, including column changes and+ * persisted or assistant-created insights, so the chart never* renders blank or plots a column against itself. A no-op when there's nothing to fix.*/const applyScatterXAxis = (@@ -613,6 +729,7 @@ export interface dataVisualizationLogicActions {transpose: boolean}setVisualizationType: (visualizationType: ChartDisplayType) => {+ node: DataVisualizationNodevisualizationType: ChartDisplayType}toggleChartSettingsPanel: (open?: boolean) => {@@ -884,7 +1001,15 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([}),props({ query: { source: {} } } as DataVisualizationLogicProps),actions(({ values }) => ({- setVisualizationType: (visualizationType: ChartDisplayType) => ({ visualizationType }),+ setVisualizationType: (visualizationType: ChartDisplayType) => ({+ visualizationType,+ node: applyVisualizationType(+ values.query,+ visualizationType,+ values.columns,+ rowCountFromResponse(values.response)+ ),+ }),updateXSeries: (columnName: string) => ({columnName,}),@@ -930,6 +1055,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([props.query,{setQuery: (state, { setter }) => setter(state),+ setVisualizationType: (_, { node }) => node,_setQuery: (_, { node }) => node,},],@@ -1015,6 +1141,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([selectedXAxis: [props.query.chartSettings?.xAxis?.column ?? null,{+ setVisualizationType: (_, { node }) => node.chartSettings?.xAxis?.column ?? null,_setQuery: (_, { node }) => node.chartSettings?.xAxis?.column ?? null,clearAxis: () => null,updateXSeries: (_, { columnName }) => columnName,@@ -1026,6 +1153,15 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([settings: cloneOrDefaultSettings(axis.settings),})) ?? null) as (SelectedYAxis | null)[] | null,{+ setVisualizationType: (state, { node }) => {+ if (node.chartSettings?.yAxis) {+ return node.chartSettings.yAxis.map((axis) => ({+ name: axis.column,+ settings: cloneOrDefaultSettings(axis.settings),+ }))+ }+ return state+ },_setQuery: (state, { node }) => {if (node.chartSettings?.yAxis) {return node.chartSettings.yAxis.map((axis) => ({@@ -1121,6 +1257,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([chartSettings: [props.query.chartSettings ?? ({} as ChartSettings),{+ setVisualizationType: (state, { node }) => node.chartSettings ?? state,_setQuery: (state, { node }) => node.chartSettings ?? state,updateChartSettings: (state, { settings }) => {return mergeChartSettings(state, settings)@@ -1250,30 +1387,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([| import('~/queries/schema/schema-general').TraceSpansAggregationQueryResponse| import('~/queries/schema/schema-general').TraceSpansAttributeBreakdownQueryResponse| import('~/queries/schema/schema-general').TraceSpansQueryResponse- ): Column[] => {- if (!response) {- return []- }-- const columns: string[] =- 'columns' in response && Array.isArray(response.columns) ? response.columns : []- const types: string[][] = 'types' in response && Array.isArray(response.types) ? response.types : []-- return columns.map((column, index) => {- const type = types[index]?.[1]- const friendlyClickhouseTypeName = toFriendlyClickhouseTypeName(type)-- return {- name: column,- type: {- name: friendlyClickhouseTypeName,- isNumerical: isNumericalType(friendlyClickhouseTypeName),- },- label: `${column} - ${type}`,- dataIndex: index,- }- })- },+ ): Column[] => columnsFromResponse(response),{ resultEqualityCheck: objectsEqual },],numericalColumns: [@@ -1737,7 +1851,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([| import('~/queries/schema/schema-general').TraceSpansAggregationQueryResponse| import('~/queries/schema/schema-general').TraceSpansAttributeBreakdownQueryResponse| import('~/queries/schema/schema-general').TraceSpansQueryResponse- ): ChartDisplayType => getAutoVisualizationType(columns, response),+ ): ChartDisplayType => getAutoVisualizationType(columns, rowCountFromResponse(response)),],isTableVisualization: [(s) => [s.effectiveVisualizationType],@@ -1823,58 +1937,8 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([props.setQuery(setter)}},- setVisualizationType: ({ visualizationType }) => {- actions.setQuery((query) => ({- ...query,- display: visualizationType,- }))-- // Newly-picked pies default to labels on slices; existing pies (loaded with the type- // already set, so this listener never fires) keep the legacy value-on-slice default.- if (- visualizationType === ChartDisplayType.ActionsPie &&- values.chartSettings.pie?.sliceContent === undefined- ) {- actions.updateChartSettings({ pie: { sliceContent: 'labels' } })- }-- if (- [ChartDisplayType.ActionsLineGraph, ChartDisplayType.ActionsAreaGraph].includes(visualizationType) &&- shouldUseFirstNumericColumnAsContinuousChartXAxis(- values.columns,- values.numericalColumns,- values.selectedXAxis,- values.selectedYAxis- )- ) {- const [xAxisColumn] = values.numericalColumns- const xAxisSeriesIndex =- values.selectedYAxis?.findIndex((series) => series?.name === xAxisColumn.name) ?? -1-- actions.updateXSeries(xAxisColumn.name)-- if (xAxisSeriesIndex > -1) {- actions.deleteYSeries(xAxisSeriesIndex)- }- }-- if (visualizationType === ChartDisplayType.ScatterPlot) {- applyScatterXAxis(actions, values.columns, values.selectedXAxis, values.selectedYAxis)- }-- if (visualizationType === ChartDisplayType.BoxPlot) {- actions.updateChartSettings({- boxPlot: getAutoBoxPlotSettings(values.columns, values.chartSettings.boxPlot),- })- }-- const isAutoHeatmap =- visualizationType === ChartDisplayType.Auto &&- getAutoVisualizationType(values.columns, values.response) === ChartDisplayType.TwoDimensionalHeatmap-- if (visualizationType === ChartDisplayType.TwoDimensionalHeatmap || isAutoHeatmap) {- applyAutoHeatmapSettings(actions, values.columns, values.chartSettings.heatmap ?? {})- }+ setVisualizationType: ({ node }) => {+ props.setQuery?.(() => node)},setTransposeResults: ({ transpose }) => {actions.setQuery((query) => ({@@ -1955,29 +2019,19 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([// Set up chart seriesif (values.response && values.selectedXAxis === null && values.selectedYAxis === null) {- const xAxisTypes = value.find((n) => n.type.name.indexOf('DATE') !== -1)- const yAxisTypes = value.filter((n) => n.type.isNumerical)-- if (yAxisTypes) {- yAxisTypes.forEach((y) => {- if (oldTabularColumnSettings) {- const lastValue = oldTabularColumnSettings.find((n) => n?.name === y.name)- return actions.addYSeries(y.name, lastValue?.settings)- }+ const { xAxis, yAxis } = deriveDefaultAxes(value)- actions.addYSeries(y.name)- })- }+ yAxis.forEach((columnName) => {+ if (oldTabularColumnSettings) {+ const lastValue = oldTabularColumnSettings.find((n) => n?.name === columnName)+ return actions.addYSeries(columnName, lastValue?.settings)+ }- if (xAxisTypes) {- actions.updateXSeries(xAxisTypes.name)- } else {- const yAxisColumnNames = new Set(yAxisTypes.map((column) => column.name))- const firstRemainingColumn = value.find((column) => !yAxisColumnNames.has(column.name))+ actions.addYSeries(columnName)+ })- if (firstRemainingColumn) {- actions.updateXSeries(firstRemainingColumn.name)- }+ if (xAxis) {+ actions.updateXSeries(xAxis)}}diff --git a/frontend/src/queries/nodes/DataVisualization/sqlVisualizationSupport.ts b/frontend/src/queries/nodes/DataVisualization/sqlVisualizationSupport.tsnew file mode 100644index 000000000000..d3bea26448c3--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/sqlVisualizationSupport.ts@@ -0,0 +1,58 @@+import { ChartDisplayType } from '~/types'++import { Column, applyVisualizationType } from './dataVisualizationLogic'++type VisualizationSupport = 'none' | 'axes' | 'manual'++const VISUALIZATION_SUPPORT: Record<ChartDisplayType, VisualizationSupport> = {+ [ChartDisplayType.Auto]: 'none',+ [ChartDisplayType.ActionsTable]: 'none',+ [ChartDisplayType.BoldNumber]: 'none',+ [ChartDisplayType.ActionsLineGraph]: 'axes',+ [ChartDisplayType.ActionsAreaGraph]: 'axes',+ [ChartDisplayType.ActionsBar]: 'axes',+ [ChartDisplayType.ActionsStackedBar]: 'axes',+ [ChartDisplayType.ActionsUnstackedBar]: 'axes',+ [ChartDisplayType.ActionsPie]: 'axes',+ [ChartDisplayType.ActionsDonut]: 'axes',+ [ChartDisplayType.ActionsLineGraphCumulative]: 'axes',+ [ChartDisplayType.ScatterPlot]: 'manual',+ [ChartDisplayType.TwoDimensionalHeatmap]: 'manual',+ [ChartDisplayType.ActionsBarValue]: 'manual',+ [ChartDisplayType.Metric]: 'manual',+ [ChartDisplayType.WorldMap]: 'manual',+ [ChartDisplayType.CalendarHeatmap]: 'manual',+ [ChartDisplayType.BoxPlot]: 'manual',+ [ChartDisplayType.SlopeGraph]: 'manual',+}++const MANUAL_SETUP_REASON = 'Open the insight to pick which column goes on each axis'++export function sqlVisualizationDisabledReason(+ displayType: ChartDisplayType,+ query: Parameters<typeof applyVisualizationType>[0],+ columns: Column[],+ rowCount: number,+ autoVisualizationType: ChartDisplayType+): string | undefined {+ const drawnAs = displayType === ChartDisplayType.Auto ? autoVisualizationType : displayType++ if (VISUALIZATION_SUPPORT[drawnAs] === 'manual') {+ return displayType === ChartDisplayType.Auto+ ? `Auto picks a chart here that needs its axes set. ${MANUAL_SETUP_REASON}.`+ : MANUAL_SETUP_REASON+ }++ if (VISUALIZATION_SUPPORT[drawnAs] !== 'axes') {+ return undefined+ }++ const nextQuery = applyVisualizationType(query, displayType, columns, rowCount)+ if (nextQuery.chartSettings?.xAxis && nextQuery.chartSettings.yAxis?.length) {+ return undefined+ }++ return nextQuery.chartSettings?.yAxis?.length+ ? 'This insight has no column left to label the X-axis'+ : 'This insight has no numeric column to plot'+}diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex de7d25cf6742..2698fc262a48 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -164,6 +164,12 @@ export function isDataVisualizationNode(node?: Record<string, any> | null): nodereturn node?.kind === NodeKind.DataVisualizationNode}+export function isDataVisualizationNodeWithHogQLQuery(+ node?: Record<string, any> | null+): node is DataVisualizationNode & { source: HogQLQuery } {+ return isDataVisualizationNode(node) && isHogQLQuery(node.source)+}+export function convertDataTableNodeToDataVisualizationNode(node: Node | null): Node | null {if (!isDataTableNodeWithHogQLQuery(node)) {return nodediff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 239b6771c730..552a66f1afb4 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -2720,6 +2720,36 @@ describe('dashboardLogic', () => {expect(updated.last_refresh).toEqual(originalLastRefresh)})+ it('preserves cached columns and types when a bare PATCH returns them null', async () => {+ // SQL tiles draw from columns and types rather than result, and pick their axes from+ // columns. Blanking those leaves the tile with nothing to draw.+ insightsModel.actions.renameInsightSuccess({+ ...insight800(),+ columns: ['day', 'total'],+ types: [+ ['day', 'DateTime'],+ ['total', 'UInt64'],+ ],+ })+ await expectLogic(logic).toFinishAllListeners()++ insightsModel.actions.renameInsightSuccess({+ ...insight800(),+ name: 'renamed via bare patch',+ columns: null,+ types: null,+ })+ await expectLogic(logic).toFinishAllListeners()++ const updated = logic.values.insightTiles[0].insight!+ expect(updated.name).toEqual('renamed via bare patch')+ expect(updated.columns).toEqual(['day', 'total'])+ expect(updated.types).toEqual([+ ['day', 'DateTime'],+ ['total', 'UInt64'],+ ])+ })+it('replaces cached chart data when a full refresh returns non-null result', async () => {const newResult = [{ data: 'fresh' }]const newLastRefresh = '2024-01-01T00:00:00Z'diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex cc55619d1f03..61a34c3577ad 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -2086,6 +2086,8 @@ export const dashboardLogic = kea<dashboardLogicType>([// A bare PATCH (rename, display-option persist) doesn't recompute the insight, so// its response carries `result: null` and stale-but-empty cache metadata. Keep the// tile's already-computed chart data instead of blanking it into "Chart data didn't load".+ // SQL insights draw from `columns` and `types` rather than `result`, so those have to+ // survive the merge too or the tile loses the columns it picks its axes from.const existing = tiles[tileIndex].insight as QueryBasedInsightModeltiles[tileIndex] = {...tiles[tileIndex],@@ -2094,6 +2096,8 @@ export const dashboardLogic = kea<dashboardLogicType>([...item,result: item.result ?? existing.result,last_refresh: item.last_refresh ?? existing.last_refresh,+ columns: item.columns ?? existing.columns,+ types: item.types ?? existing.types,},}diff --git a/frontend/src/scenes/insights/insightDataLogic.test.ts b/frontend/src/scenes/insights/insightDataLogic.test.tsindex 853c7cea1a3e..c1630072369e 100644--- a/frontend/src/scenes/insights/insightDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightDataLogic.test.ts@@ -7,6 +7,7 @@ jest.mock('~/queries/query', () => ({import { MOCK_TEAM_ID } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightLogic } from 'scenes/insights/insightLogic'@@ -20,6 +21,7 @@ import { examples } from '~/queries/examples'import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'import { performQuery } from '~/queries/query'import {+ DataVisualizationNode,FunnelsQuery,InsightVizNode,Node,@@ -29,7 +31,7 @@ import {} from '~/queries/schema/schema-general'import { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'-import { FunnelVizType, InsightShortId, InsightType } from '~/types'+import { ChartDisplayType, FunnelVizType, InsightShortId, InsightType } from '~/types'import { insightDataLogic } from './insightDataLogic'@@ -37,6 +39,10 @@ const mockedPerformQuery = performQuery as jest.MockedFunction<typeof performQueconst Insight123 = '123' as InsightShortId+function capturesOf(event: string): any[][] {+ return (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === event)+}+describe('insightDataLogic', () => {let theInsightDataLogic: ReturnType<typeof insightDataLogic.build>let theInsightLogic: ReturnType<typeof insightLogic.build>@@ -597,6 +603,253 @@ describe('insightDataLogic', () => {})})+ describe('persistSqlVisualization', () => {+ const insightId = 43+ const Insight43 = '43' as InsightShortId+ const cachedQuery = {+ kind: NodeKind.DataVisualizationNode,+ source: { kind: NodeKind.HogQLQuery, query: 'select day, total from events' },+ display: ChartDisplayType.ActionsTable,+ } as DataVisualizationNode+ const latestQuery = {+ kind: NodeKind.DataVisualizationNode,+ source: { kind: NodeKind.HogQLQuery, query: 'select day, total from events' },+ display: ChartDisplayType.ActionsTable,+ chartSettings: {+ xAxis: { column: 'day' },+ yAxis: [{ column: 'total' }],+ showLegend: false,+ },+ } as DataVisualizationNode++ let logic: ReturnType<typeof insightDataLogic.build>+ let patchBodies: Record<string, any>[]+ let savedQuery: Node+ let patchFails: boolean++ beforeEach(() => {+ ;(posthog.capture as jest.Mock).mockClear()+ patchBodies = []+ savedQuery = latestQuery+ patchFails = false+ useMocks({+ get: {+ '/api/environments/:team_id/insights/': () => [+ 200,+ { results: [{ id: insightId, short_id: Insight43, query: savedQuery }] },+ ],+ },+ patch: {+ '/api/environments/:team_id/insights/:id': async ({ request }) => {+ const body = (await request.json()) as Record<string, any>+ patchBodies.push(body)+ if (patchFails) {+ return [500, { detail: 'Save failed' }]+ }+ return [200, { id: insightId, short_id: Insight43, ...body }]+ },+ },+ })++ const props = {+ dashboardItemId: Insight43,+ cachedInsight: { id: insightId, short_id: Insight43, query: cachedQuery } as any,+ }+ insightsModel.mount()+ insightLogic(props).mount()+ logic = insightDataLogic(props)+ logic.mount()+ logic.actions.setInsightData({+ columns: ['day', 'total'],+ types: [+ ['day', 'DateTime'],+ ['total', 'UInt64'],+ ],+ results: [+ ['2026-08-27', 12],+ ['2026-08-28', 15],+ ],+ })+ })++ it('derives the picked chart from the latest clean query and loaded tile schema', async () => {+ await expectLogic(logic, () => {+ logic.actions.persistSqlVisualization({+ type: 'chart-type',+ display: ChartDisplayType.ActionsLineGraph,+ })+ })+ .toFinishAllListeners()+ .toDispatchActions(['renameInsightSuccess'])++ expect(patchBodies).toHaveLength(1)+ expect(patchBodies[0].query).toMatchObject({+ source: latestQuery.source,+ display: ChartDisplayType.ActionsLineGraph,+ chartSettings: {+ xAxis: { column: 'day' },+ yAxis: [{ column: 'total' }],+ showLegend: false,+ },+ })+ expect(capturesOf('dashboard_sql_visualization_changed')).toEqual([+ [+ 'dashboard_sql_visualization_changed',+ { insight_id: insightId, type: 'chart-type', display: 'ActionsLineGraph' },+ ],+ ])+ })++ it.each([+ ['has no columns', { columns: [], types: [], results: [] }, 'no_columns'],+ [+ 'no longer supports the picked chart',+ { columns: ['country'], types: [['country', 'String']], results: [['NL']] },+ 'unsupported',+ ],+ ])('does not save when the latest SQL result %s', async (_condition, response, reason) => {+ logic.actions.setInsightData(response)++ await expectLogic(logic, () => {+ logic.actions.persistSqlVisualization({+ type: 'chart-type',+ display: ChartDisplayType.ActionsLineGraph,+ })+ }).toFinishAllListeners()++ expect(patchBodies).toHaveLength(0)+ expect(logic.values.savingSqlVisualization).toBeNull()+ expect(capturesOf('dashboard_sql_visualization_failed')).toEqual([+ ['dashboard_sql_visualization_failed', { insight_id: insightId, type: 'chart-type', reason }],+ ])+ })++ it('does not combine a changed saved query with the loaded tile schema', async () => {+ savedQuery = {+ ...latestQuery,+ source: { kind: NodeKind.HogQLQuery, query: 'select country from events' },+ } as DataVisualizationNode++ await expectLogic(logic, () => {+ logic.actions.persistSqlVisualization({+ type: 'chart-type',+ display: ChartDisplayType.ActionsLineGraph,+ })+ }).toFinishAllListeners()++ expect(patchBodies).toHaveLength(0)+ expect(logic.values.savingSqlVisualization).toBeNull()+ expect(capturesOf('dashboard_sql_visualization_failed')).toEqual([+ [+ 'dashboard_sql_visualization_failed',+ { insight_id: insightId, type: 'chart-type', reason: 'mismatch' },+ ],+ ])+ })++ it('does not overwrite an insight that changed away from SQL', async () => {+ savedQuery = { kind: NodeKind.EventsQuery }++ await expectLogic(logic, () => {+ logic.actions.persistSqlVisualization({+ type: 'chart-type',+ display: ChartDisplayType.ActionsLineGraph,+ })+ }).toFinishAllListeners()++ expect(patchBodies).toHaveLength(0)+ expect(logic.values.savingSqlVisualization).toBeNull()+ })++ it('persists only the last display edit against the latest clean SQL query', async () => {+ savedQuery = {+ ...latestQuery,+ source: { ...latestQuery.source, variables: {} },+ } as DataVisualizationNode+ const dashboardQuery = {+ ...cachedQuery,+ source: {+ ...cachedQuery.source,+ filters: { dateRange: { date_from: '-7d' } },+ },+ } as DataVisualizationNode+ logic.actions.syncQueryFromProps(dashboardQuery)++ logic.actions.persistSqlVisualization({+ type: 'display-options',+ query: {+ ...dashboardQuery,+ chartSettings: { ...latestQuery.chartSettings, showLegend: true },+ },+ })+ logic.actions.persistSqlVisualization({+ type: 'display-options',+ query: {+ ...dashboardQuery,+ chartSettings: { ...latestQuery.chartSettings, showLegend: false, xAxisLabel: 'Day' },+ },+ })+ expect(logic.values.savingSqlVisualization).toBe('display-options')++ await expectLogic(logic).toFinishAllListeners().toDispatchActions(['renameInsightSuccess'])++ expect(patchBodies).toHaveLength(1)+ expect(patchBodies[0].query).toEqual({+ ...savedQuery,+ chartSettings: { ...latestQuery.chartSettings, showLegend: false, xAxisLabel: 'Day' },+ })+ expect(logic.values.savingSqlVisualization).toBeNull()+ expect(capturesOf('dashboard_sql_visualization_changed')).toEqual([+ [+ 'dashboard_sql_visualization_changed',+ { insight_id: insightId, type: 'display-options', display: 'ActionsTable' },+ ],+ ])+ })++ it('does not persist display settings from a stale chart type', async () => {+ savedQuery = {+ ...latestQuery,+ display: ChartDisplayType.ActionsPie,+ } as DataVisualizationNode++ await expectLogic(logic, () => {+ logic.actions.persistSqlVisualization({+ type: 'display-options',+ query: {+ ...cachedQuery,+ chartSettings: { showLegend: true },+ },+ })+ }).toFinishAllListeners()++ expect(patchBodies).toHaveLength(0)+ })++ it('invalidates optimistic display controls when their save fails', async () => {+ patchFails = true++ await expectLogic(logic, () => {+ logic.actions.persistSqlVisualization({+ type: 'display-options',+ query: {+ ...cachedQuery,+ chartSettings: { showLegend: true },+ },+ })+ }).toFinishAllListeners()++ expect(logic.values.sqlVisualizationVersion).toBe(1)+ expect(logic.values.savingSqlVisualization).toBeNull()+ expect(capturesOf('dashboard_sql_visualization_failed')).toEqual([+ [+ 'dashboard_sql_visualization_failed',+ { insight_id: insightId, type: 'display-options', reason: 'error' },+ ],+ ])+ })+ })+describe('draft query persistence', () => {const draftKey = `draft-query-${MOCK_TEAM_ID}`const newInsightQuery = (mutate?: (query: any) => void): Node => {diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsxindex ed560d6f009a..895c61bbbd1b 100644--- a/frontend/src/scenes/insights/insightDataLogic.tsx+++ b/frontend/src/scenes/insights/insightDataLogic.tsx@@ -15,6 +15,7 @@ import {} from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, router } from 'kea-router'+import posthog from 'posthog-js'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -30,6 +31,13 @@ import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'import { insightsModel } from '~/models/insightsModel'import { examples } from '~/queries/examples'import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import {+ applyVisualizationType,+ columnsFromResponse,+ getAutoVisualizationType,+ rowCountFromResponse,+} from '~/queries/nodes/DataVisualization/dataVisualizationLogic'+import { sqlVisualizationDisabledReason } from '~/queries/nodes/DataVisualization/sqlVisualizationSupport'import { nodeKindToInsightType } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'import { getDefaultQuery, queryFromKind } from '~/queries/nodes/InsightViz/utils'@@ -38,6 +46,7 @@ import { DataVisualizationNode, HogQLVariable, InsightVizNode, Node, NodeKind }import {isDataTableNode,isDataVisualizationNode,+ isDataVisualizationNodeWithHogQLQuery,isHogQLQuery,isHogQuery,isInsightQueryNode,@@ -45,7 +54,7 @@ import {isWebAnalyticsInsightQuery,shouldQueryBeAsync,} from '~/queries/utils'-import { ExportContext, InsightLogicProps, InsightType } from '~/types'+import { ChartDisplayType, ExportContext, InsightLogicProps, InsightType } from '~/types'import { DATAWAREHOUSE_EDITOR_ITEM_ID } from 'products/data_warehouse/frontend/utils'@@ -94,6 +103,21 @@ export const isInsightSceneInstance = (props: InsightLogicProps): boolean =>sceneLogic.values.activeSceneId === Scene.Insight &&insightSceneLogic.findMounted()?.values.insightLogicRef?.logic.key === keyForInsightLogicProps('new')(props)+const isMatchingSqlQuery = (+ query: Node | null | undefined,+ reference: Node | null | undefined+): query is DataVisualizationNode =>+ !!query &&+ isDataVisualizationNodeWithHogQLQuery(query) &&+ !!reference &&+ isDataVisualizationNodeWithHogQLQuery(reference) &&+ query.source.query === reference.source.query &&+ objectsEqual(query.source.variables ?? {}, reference.source.variables ?? {})++export type SqlVisualizationUpdate =+ | { type: 'chart-type'; display: ChartDisplayType }+ | { type: 'display-options'; query: DataVisualizationNode }+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface insightDataLogicValues {getInsightRefreshButtonDisabledReason: () => string // dataNodeLogic@@ -138,8 +162,10 @@ export interface insightDataLogicValues {query: Node | nullqueryChanged: booleanqueryFromUrl: boolean+ savingSqlVisualization: SqlVisualizationUpdate['type'] | nullshowDebugPanel: booleanshowQueryEditor: boolean+ sqlVisualizationVersion: number}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -250,6 +276,7 @@ export interface insightDataLogicActions {_create_in_folder?: string | null | undefinedalerts?: AlertType[] | undefinedcache_target_age?: string | null | undefined+ columns?: string[] | null | undefinedcreated_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null@@ -279,6 +306,7 @@ export interface insightDataLogicActions {short_id: InsightShortIdtags?: string[] | undefinedtimezone?: string | null | undefined+ types?: string[][] | null | undefinedupdated_at: stringuser_access_level: AccessControlLevelview_count?: number | undefined@@ -297,6 +325,7 @@ export interface insightDataLogicActions {_create_in_folder?: string | null | undefinedalerts?: AlertType[] | undefinedcache_target_age?: string | null | undefined+ columns?: string[] | null | undefinedcreated_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null@@ -326,6 +355,7 @@ export interface insightDataLogicActions {short_id: InsightShortIdtags?: string[] | undefinedtimezone?: string | null | undefined+ types?: string[][] | null | undefinedupdated_at: stringuser_access_level: AccessControlLevelview_count?: number | undefined@@ -384,6 +414,15 @@ export interface insightDataLogicActions {persistDisplayOptions: (query: Node) => {query: Node<Record<string, any>>}+ persistSqlVisualization: (update: SqlVisualizationUpdate) => {+ update: SqlVisualizationUpdate+ }+ persistSqlVisualizationFailed: (update: SqlVisualizationUpdate) => {+ update: SqlVisualizationUpdate+ }+ persistSqlVisualizationSettled: () => {+ value: true+ }setQuery: (query: Node | null,fromUrl?: boolean@@ -502,9 +541,26 @@ export const insightDataLogic = kea<insightDataLogicType>([toggleDebugPanel: true,cancelChanges: true,persistDisplayOptions: (query: Node) => ({ query }),+ persistSqlVisualization: (update: SqlVisualizationUpdate) => ({ update }),+ persistSqlVisualizationFailed: (update: SqlVisualizationUpdate) => ({ update }),+ persistSqlVisualizationSettled: true,}),reducers({+ savingSqlVisualization: [+ null as SqlVisualizationUpdate['type'] | null,+ {+ persistSqlVisualization: (_, { update }) => update.type,+ persistSqlVisualizationFailed: () => null,+ persistSqlVisualizationSettled: () => null,+ },+ ],+ sqlVisualizationVersion: [+ 0,+ {+ persistSqlVisualizationFailed: (state) => state + 1,+ },+ ],internalQuery: [null as Node | null,{@@ -725,7 +781,7 @@ export const insightDataLogic = kea<insightDataLogicType>([persistDisplayOptions: async ({ query }, breakpoint) => {// Never auto-persist while the user is editing this insight in the insight scene.// insightDataLogic is keyed `${shortId}/on-dashboard-${dashboardId}`, so an insight- // opened from a dashboard shares its instance with the dashboard tile — which wired+ // opened from a dashboard shares its instance with the dashboard tile, which wired// props.setQuery to persistDisplayOptions. Without this guard, any edit in the scene// (a display toggle or removing a filter) would PATCH the insight before the user// clicks Save. Edits there must persist only through an explicit save.@@ -733,7 +789,7 @@ export const insightDataLogic = kea<insightDataLogicType>([return}// Debounce rapid clicks. insightDataLogic is keyed per insight, so breakpoint- // only cancels concurrent saves for THIS insight — not unrelated tiles.+ // only cancels concurrent saves for this insight without affecting unrelated tiles.await breakpoint(700)const insightId = values.insight.idif (!insightId) {@@ -741,7 +797,7 @@ export const insightDataLogic = kea<insightDataLogicType>([}// Only persist when the query actually differs from what's saved. The setQuery →// props.setQuery path fires for any InsightVizNode change, including programmatic- // re-syncs (tile re-renders, results refreshes) that carry an unchanged query —+ // re-syncs (tile re-renders, results refreshes) that carry an unchanged query;// persisting those produces spurious saves and activity-log churn.if (objectsEqual(query, values.savedInsight.query)) {return@@ -753,12 +809,103 @@ export const insightDataLogic = kea<insightDataLogicType>([actions.renameInsightSuccess(updatedItem)lemonToast.success('Insight updated')} catch (e) {+ // A breakpoint means a newer save superseded this one, and that save owns the state.if (!isBreakpoint(e as Error)) {lemonToast.error('Failed to update insight')}}},+ persistSqlVisualization: async ({ update }, breakpoint) => {+ const fail = (reason: 'mismatch' | 'unsupported' | 'no_columns' | 'error'): void => {+ actions.persistSqlVisualizationFailed(update)+ posthog.capture('dashboard_sql_visualization_failed', {+ insight_id: values.insight.id,+ type: update.type,+ reason,+ })+ lemonToast.error(+ update.type === 'chart-type'+ ? "Couldn't update chart type. Refresh the dashboard and try again."+ : "Couldn't update display options. Refresh the dashboard and try again."+ )+ }++ if (isInsightSceneInstance(props)) {+ actions.persistSqlVisualizationSettled()+ return+ }++ try {+ await breakpoint(update.type === 'display-options' ? 700 : 0)+ const insightId = values.insight.id+ const shortId = values.insight.short_id+ if (!insightId || !shortId) {+ actions.persistSqlVisualizationSettled()+ return+ }++ const savedQuery = (await insightsApi.getByShortId(shortId, true))?.query+ if (!isMatchingSqlQuery(savedQuery, values.query)) {+ fail('mismatch')+ return+ }++ let nextQuery: DataVisualizationNode+ if (update.type === 'chart-type') {+ const columns = columnsFromResponse(values.insightData)+ const rowCount = rowCountFromResponse(values.insightData)+ const autoVisualizationType = getAutoVisualizationType(columns, rowCount)+ if (columns.length === 0) {+ fail('no_columns')+ return+ }+ if (+ sqlVisualizationDisabledReason(+ update.display,+ savedQuery,+ columns,+ rowCount,+ autoVisualizationType+ )+ ) {+ fail('unsupported')+ return+ }+ nextQuery = applyVisualizationType(savedQuery, update.display, columns, rowCount)+ } else {+ if (+ !isMatchingSqlQuery(update.query, values.query) ||+ savedQuery.display !== update.query.display+ ) {+ fail('mismatch')+ return+ }+ nextQuery = { ...savedQuery, chartSettings: update.query.chartSettings }+ }++ if (objectsEqual(nextQuery, savedQuery)) {+ actions.persistSqlVisualizationSettled()+ return+ }++ const updatedItem = await insightsApi.update(insightId, { query: nextQuery })+ await breakpoint(0)+ actions.renameInsightSuccess(updatedItem)+ actions.persistSqlVisualizationSettled()+ posthog.capture('dashboard_sql_visualization_changed', {+ insight_id: insightId,+ type: update.type,+ display: update.type === 'chart-type' ? update.display : update.query.display,+ })+ lemonToast.success('Insight updated')+ } catch (e) {+ if (!isBreakpoint(e as Error)) {+ fail('error')+ }+ }+ },+generateInsightMetadataSuccess: ({ generatedInsightMetadata }) => {if (generatedInsightMetadata) {actions.setInsightMetadata({@@ -792,7 +939,7 @@ export const insightDataLogic = kea<insightDataLogicType>([}// `internalQuery` wins over `insight.query` in the `query` selector, and the SQL editor- // updates a different logic instance — so a reload alone leaves this scene on the stale+ // updates a different logic instance, so a reload alone leaves this scene on the stale// query until a hard refresh. Re-sync the override to the freshly loaded query.if (insight.query && !objectsEqual(insight.query, values.query)) {actions.syncQueryFromProps(insight.query)@@ -842,7 +989,7 @@ export const insightDataLogic = kea<insightDataLogicType>([// a draft that only differs from the type's default in cosmetic ways (or that the// editor marks as changed by construction) is noise when resurfaced as "unsaved insight"if (!isDraftQueryWorthSaving(query, values.filterTestAccountsDefault)) {- // reverting a meaningful edit supersedes the draft this editor persisted — but an+ // reverting a meaningful edit supersedes the draft this editor persisted, but an// editor that never persisted one must not delete a draft from an earlier sessionif (cache.persistedDraftQuery) {cache.persistedDraftQuery = false@@ -893,7 +1040,7 @@ export const insightDataLogic = kea<insightDataLogicType>([return}// On dashboard tiles props.setQuery persists edits, and `setQuery` is shared with- // insightVizDataLogic whose listener calls props.setQuery — so re-syncing a stale incoming+ // insightVizDataLogic whose listener calls props.setQuery, so re-syncing a stale incoming// cached query (e.g. from a tile results refresh) via setQuery loops back and PATCHes it,// reverting a just-saved display option. syncQueryFromProps updates local state without the// loop. The insight scene keeps setQuery for its URL/draft sync.diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex 0fd3ecac1098..0e15272d17f3 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -189,6 +189,7 @@ export interface insightLogicActions {_create_in_folder?: string | null | undefinedalerts?: AlertType[] | undefinedcache_target_age?: string | null | undefined+ columns?: string[] | null | undefinedcreated_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null@@ -218,6 +219,7 @@ export interface insightLogicActions {short_id: InsightShortIdtags?: string[] | undefinedtimezone?: string | null | undefined+ types?: string[][] | null | undefinedupdated_at: stringuser_access_level: AccessControlLevelview_count?: number | undefined@@ -234,6 +236,7 @@ export interface insightLogicActions {_create_in_folder?: string | null | undefinedalerts?: AlertType[] | undefinedcache_target_age?: string | null | undefined+ columns?: string[] | null | undefinedcreated_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null@@ -263,6 +266,7 @@ export interface insightLogicActions {short_id: InsightShortIdtags?: string[] | undefinedtimezone?: string | null | undefined+ types?: string[][] | null | undefinedupdated_at: stringuser_access_level: AccessControlLevelview_count?: number | undefined@@ -356,6 +360,7 @@ export interface insightLogicActions {_create_in_folder?: string | null | undefinedalerts?: AlertType[] | undefinedcache_target_age?: string | null | undefined+ columns?: string[] | null | undefinedcreated_at?: string | undefinedcreated_by?: UserBasicType | null | undefineddashboard_tiles?: DashboardTileBasicType[] | null | undefined@@ -385,6 +390,7 @@ export interface insightLogicActions {short_id?: InsightShortId | undefinedtags?: string[] | undefinedtimezone?: string | null | undefined+ types?: string[][] | null | undefinedupdated_at?: string | undefineduser_access_level?: AccessControlLevel | undefinedview_count?: number | undefined@@ -400,6 +406,7 @@ export interface insightLogicActions {_create_in_folder?: string | null | undefinedalerts?: AlertType[] | undefinedcache_target_age?: string | null | undefined+ columns?: string[] | null | undefinedcreated_at?: string | undefinedcreated_by?: UserBasicType | null | undefineddashboard_tiles?: DashboardTileBasicType[] | null | undefined@@ -429,6 +436,7 @@ export interface insightLogicActions {short_id?: InsightShortId | undefinedtags?: string[] | undefinedtimezone?: string | null | undefined+ types?: string[][] | null | undefinedupdated_at?: string | undefineduser_access_level?: AccessControlLevel | undefinedview_count?: number | undefineddiff --git a/frontend/src/scenes/saved-insights/activityDescriptions.tsx b/frontend/src/scenes/saved-insights/activityDescriptions.tsxindex 67657637e5ec..8f233a9ce296 100644--- a/frontend/src/scenes/saved-insights/activityDescriptions.tsx+++ b/frontend/src/scenes/saved-insights/activityDescriptions.tsx@@ -259,6 +259,8 @@ const insightActionsMapping: Record<view_count: () => null,is_cached: () => null,filter_override_context: () => null,+ columns: () => null,+ types: () => null,resolved_date_range: () => null,}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 1b70d9a57243..19534775ba6c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2618,6 +2618,10 @@ export interface InsightModel extends Cacheable, WithAccessControl {favorited?: booleanorder: number | nullresult: any+ /** Result column names, served alongside `result`. SQL insights draw from these. */+ columns?: string[] | null+ /** ClickHouse type of each entry in `columns`, as [name, type] pairs. */+ types?: string[][] | nulldeleted: booleansaved: booleancreated_at: string