Skip to content

: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.

feat(insights): edit SQL insight {filters} in view mode (#73375)

Thomas Obermüller5c650b0ba794
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 35c361a76b82..c22ac300f82d 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -744,6 +744,40 @@ describe('sqlEditorLogic', () => {
expect(editorRootLogic.values.updateInsightButtonEnabled).toEqual(false)
})
+ it('applies filters from the URL hash on top of the opened insight so view-mode filter edits can be saved', async () => {
+ // The insight scene's Edit button carries unsaved view-mode filter edits via
+ // urls.sqlEditor({ insightShortId, filters }) — they must land in sourceQuery
+ // (not the saved insight's filters) with the tab still bound to the insight,
+ // so Update insight is enabled and persists them.
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
+
+ const filters: HogQLFilters = { dateRange: { date_from: '-30d', date_to: null } }
+ router.actions.push(urls.sqlEditor({ insightShortId: MOCK_INSIGHT_SHORT_ID, filters }))
+
+ await expectLogic(logic)
+ .toDispatchActions(['editInsight', 'createTab', 'updateTab'])
+ .toMatchValues({
+ editingInsight: partial({
+ short_id: MOCK_INSIGHT_SHORT_ID,
+ }),
+ sourceQuery: partial({
+ source: partial({
+ query: (MOCK_INSIGHT_QUERY.source as HogQLQuery).query,
+ filters: partial({ dateRange: partial({ date_from: '-30d' }) }),
+ }),
+ }),
+ })
+
+ expect(editorRootLogic.values.updateInsightButtonEnabled).toEqual(true)
+ })
+
it('enables Update insight as soon as sourceQuery diverges from the saved insight, even when dataVisualizationLogic mirror lags behind', async () => {
logic = sqlEditorLogic({
tabId: TAB_ID,
diff --git a/frontend/src/scenes/insights/InsightAsScene.tsx b/frontend/src/scenes/insights/InsightAsScene.tsx
index 18945f52729b..1b1cd0fc8973 100644
--- a/frontend/src/scenes/insights/InsightAsScene.tsx
+++ b/frontend/src/scenes/insights/InsightAsScene.tsx
@@ -20,6 +20,7 @@ import { insightDataLogic } from './insightDataLogic'
import { insightLogic } from './insightLogic'
import { InsightSceneHeader } from './InsightSceneHeader'
import { insightVizDataLogic } from './insightVizDataLogic'
+import { SqlInsightFilters } from './SqlInsightFilters'
export interface InsightAsSceneProps {
insightId: InsightShortId | 'new'
@@ -91,28 +92,30 @@ export function InsightAsScene({ insightId, attachTo }: InsightAsSceneProps): JS
<InsightRetentionBanner insightProps={insightProps} />
- {isDataVisualizationNode(query) && insightLoading ? (
- // Avoid painting the stale chart type during a reload (the query re-syncs in insightDataLogic).
- <LemonSkeleton className="h-100 w-full" />
- ) : (
- <Query
- attachTo={attachTo}
- query={isInsightVizNode(query) ? { ...query, full: true } : query}
- setQuery={setQuery}
- readOnly={insightMode !== ItemMode.Edit}
- editMode={insightMode === ItemMode.Edit}
- context={{
- showOpenEditorButton: false,
- showQueryEditor: actuallyShowQueryEditor,
- showQueryHelp: insightMode === ItemMode.Edit && !containsHogQLQuery(query),
- insightProps,
- // Flag-gated inside the charts' shared useDateRangeZoom hook.
- onDateRangeZoom: zoomDateRange,
- }}
- filtersOverride={filtersOverride}
- variablesOverride={variablesOverride}
- />
- )}
+ <SqlInsightFilters query={query} setQuery={setQuery}>
+ {isDataVisualizationNode(query) && insightLoading ? (
+ // Avoid painting the stale chart type during a reload (the query re-syncs in insightDataLogic).
+ <LemonSkeleton className="h-100 w-full" />
+ ) : (
+ <Query
+ attachTo={attachTo}
+ query={isInsightVizNode(query) ? { ...query, full: true } : query}
+ setQuery={setQuery}
+ readOnly={insightMode !== ItemMode.Edit}
+ editMode={insightMode === ItemMode.Edit}
+ context={{
+ showOpenEditorButton: false,
+ showQueryEditor: actuallyShowQueryEditor,
+ showQueryHelp: insightMode === ItemMode.Edit && !containsHogQLQuery(query),
+ insightProps,
+ // Flag-gated inside the charts' shared useDateRangeZoom hook.
+ onDateRangeZoom: zoomDateRange,
+ }}
+ filtersOverride={filtersOverride}
+ variablesOverride={variablesOverride}
+ />
+ )}
+ </SqlInsightFilters>
</SceneContent>
</BindLogic>
)
diff --git a/frontend/src/scenes/insights/InsightPageHeader.tsx b/frontend/src/scenes/insights/InsightPageHeader.tsx
index 927dd7b8ab10..b70f2ed32146 100644
--- a/frontend/src/scenes/insights/InsightPageHeader.tsx
+++ b/frontend/src/scenes/insights/InsightPageHeader.tsx
@@ -203,6 +203,8 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In
urls.sqlEditor({
insightShortId: insight.short_id,
dashboard: dashboardId ?? undefined,
+ // Carry unsaved view-mode filter edits into the editor so they can be saved
+ filters: queryChanged ? query.source.filters : undefined,
})
)
} else if (insight.short_id) {
diff --git a/frontend/src/scenes/insights/SqlInsightFilters.tsx b/frontend/src/scenes/insights/SqlInsightFilters.tsx
new file mode 100644
index 000000000000..7d2f48ea16d2
--- /dev/null
+++ b/frontend/src/scenes/insights/SqlInsightFilters.tsx
@@ -0,0 +1,90 @@
+import { useValues } from 'kea'
+import { ReactNode } from 'react'
+
+import { IconCalendar } from '@posthog/icons'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { dateMapping } from 'lib/utils/dateFilters'
+import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
+
+import { EventPropertyFilters } from '~/queries/nodes/EventsNode/EventPropertyFilters'
+import { HogQLQuery, Node } from '~/queries/schema/schema-general'
+import { isDataTableNode, isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'
+import { ItemMode } from '~/types'
+
+const FILTERS_PLACEHOLDER = /\{\s*filters\b/
+
+function hogQLSource(query: Node | null): HogQLQuery | null {
+ const source = isDataVisualizationNode(query) || isDataTableNode(query) ? query.source : query
+ return isHogQLQuery(source) ? source : null
+}
+
+interface SqlInsightFiltersProps {
+ query: Node | null
+ setQuery: (query: Node) => void
+ children: ReactNode
+}
+
+/**
+ * Date range and property filters for SQL insights whose query uses the `{filters}` placeholder,
+ * shown in view mode inside the classic insight card. Edits update the query's `filters` in local
+ * state and re-run it — exactly how changing the date on any other saved insight works. The saved
+ * insight only changes when the user saves.
+ */
+export function SqlInsightFilters({ query, setQuery, children }: SqlInsightFiltersProps): JSX.Element {
+ const { insightMode } = useValues(insightSceneLogic)
+
+ const source = hogQLSource(query)
+ if (insightMode !== ItemMode.View || !query || !source || !FILTERS_PLACEHOLDER.test(source.query)) {
+ return <>{children}</>
+ }
+
+ const setSource = (newSource: HogQLQuery): void => {
+ if (isDataVisualizationNode(query) || isDataTableNode(query)) {
+ const nextQuery = { ...query, source: newSource }
+ setQuery(nextQuery)
+ } else {
+ setQuery(newSource)
+ }
+ }
+
+ return (
+ <div
+ className="InsightVizDisplay InsightVizDisplay--type-trends border rounded bg-surface-primary"
+ data-attr="sql-insight-filters"
+ >
+ {/* Mirrors InsightDisplayConfig's markup so the header matches classic insights */}
+ <div className="InsightDisplayConfig @container flex justify-between items-center flex-wrap gap-2 [&_.LemonButton--small]:[--lemon-button-gap:0.25rem] [&_.LemonButton--small]:[--lemon-button-padding-horizontal:0.375rem]">
+ <div className="flex items-center gap-x-2 flex-wrap gap-y-2">
+ <span className="flex items-center gap-x-2 text-sm">
+ <DateFilter
+ showExplicitDateToggle
+ allowTimePrecision
+ allowFixedRangeWithTime
+ dateFrom={source.filters?.dateRange?.date_from ?? null}
+ dateTo={source.filters?.dateRange?.date_to ?? null}
+ explicitDate={source.filters?.dateRange?.explicitDate ?? false}
+ onChange={(date_from, date_to, explicitDate) =>
+ setSource({
+ ...source,
+ filters: { ...source.filters, dateRange: { date_from, date_to, explicitDate } },
+ })
+ }
+ dateOptions={dateMapping}
+ allowedRollingDateOptions={['hours', 'days', 'weeks', 'months', 'years']}
+ makeLabel={(key) => (
+ <>
+ <IconCalendar /> {key}
+ </>
+ )}
+ />
+ </span>
+ <span className="flex items-center gap-x-2 text-sm">
+ <EventPropertyFilters query={source} setQuery={setSource} />
+ </span>
+ </div>
+ </div>
+ <div className="InsightVizDisplay__content">{children}</div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index b48ad86b2c42..d5633b1dd023 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -6,6 +6,7 @@ import { fileSystemTypes, productUrls } from '~/products'
import {
DataTableNode,
DataVisualizationNode,
+ HogQLFilters,
ProductKey,
SharingConfigurationSettings,
} from '~/queries/schema/schema-general'
@@ -76,6 +77,7 @@ export const urls = {
source,
connectionId,
dashboard,
+ filters,
}: {
/** Raw SQL, or a node whose visualization settings (display, chartSettings) should survive the trip */
query?: string | DataVisualizationNode | DataTableNode
@@ -87,6 +89,8 @@ export const urls = {
source?: string
connectionId?: string
dashboard?: number
+ /** Applied on top of the opened query/insight — carries unsaved view-mode filter edits into the editor */
+ filters?: HogQLFilters
} = {}): string => {
const params = new URLSearchParams()
@@ -121,6 +125,9 @@ export const urls = {
if (connectionId) {
hashParams.set('c', connectionId)
}
+ if (filters) {
+ hashParams.set('filters', JSON.stringify(filters))
+ }
const hashString = hashParams.toString()
return `/sql${queryString ? `?${queryString}` : ''}${hashString ? `#${hashString}` : ''}`