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(bi): preview worksheet sql and open it in the editor (#117761)

Marius Andra96137da52005
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index be67bb4d2208..627a297453ca 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -58,6 +58,8 @@ BI usage keeps the existing `sql-editor-bi-mode-selected`, `sql-editor-bi-query-
For older saves without worksheet configuration, discarding query edits preserves the current source and shelves.
+Choose **View SQL** from the worksheet actions menu to inspect and copy either the current worksheet query or its last-run query. Pending changes are labeled. The SQL includes the extra result group used to detect truncated results. **Open in SQL editor** opens an unsaved SQL tab with the selected query's connection, filters, variable values, and query options intact. It does not run the query or create a warehouse view. Copying SQL copies the text only; the preview lists its query parameters separately. Relative date ranges are evaluated again on the next run.
+
SQL query-scan advisories are hidden in Business intelligence. Query errors and warnings about stale sources or restricted data remain visible.
Saving a worksheet preserves its connection, table, shelves, measures, filters, chart type, limit, sort order, and visualization settings in a `BIVisualizationNode`. The wrapper contains the worksheet configuration and a plain `HogQLQuery` source. Member aliases, filter labels, ungrouped member handling, and hierarchy drill paths are optional saved definitions; existing worksheets keep their defaults. Saving keeps the worksheet in the BI editor; dashboard tiles can still use the normal insight view. **Edit** reopens Business intelligence when the feature is enabled, including from a dashboard. Leaving a worksheet with unsaved edits asks for confirmation, including when returning to **Worksheets**. **Discard changes** restores the saved worksheet. **Save as SQL view** exports only the generated SQL to a warehouse view; save a worksheet to retain editable worksheet state.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 43001b83ea03..3616390353b8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6766,6 +6766,10 @@ snapshots:
hash: v1.k794b7964.f9498533f26dcbda10f7e4061038e713a7325f635743eb9977bcdd7cc4a04ae0.uhcKGOmcxsxznbzt19e2cZZcN3lNE-9cSBy5VlVq0pU
products-business-intelligence-worksheet-exploration--scatter-selection--light:
hash: v1.k794b7964.2f3dee4b9e5f3f86f8d5639a380f16dfa8be646209b4a859d4476e6d2217c344.uykpvzQ3tWg2uGnQUAxfwrDNYlVHEI9zfqjWeaLCtuo
+ products-business-intelligence-worksheet-exploration--sql-preview--dark:
+ hash: v1.k794b7964.0c799dde5f45d0132adea9cd565d4ef7d074b78255da1138a1b9c76b5030373c.1fmdtlQ1z0XQlGBswx8rJNK2wmfkwWYd-WdqLJaAMyg
+ products-business-intelligence-worksheet-exploration--sql-preview--light:
+ hash: v1.k794b7964.65bca19aec73213bc3606b3703ac40d96e5b19a4c917b71b42081b6a59b113f2.1WFaE2x0Bhl2SnlkCWQgHOYAf07GR4IisxPxFuF4jEY
products-business-intelligence-worksheets--worksheets--dark:
hash: v1.k794b7964.3998501a45652d1982a4ae8217c905e0482c6979a4f54642cbc8739d991730ef.x5TzvSg7zyGoyTdnBYKHG__tv6ytXrmifpxCAgkyItg
products-business-intelligence-worksheets--worksheets--light:
diff --git a/products/business_intelligence/frontend/BISQLPreviewModal.tsx b/products/business_intelligence/frontend/BISQLPreviewModal.tsx
new file mode 100644
index 000000000000..ec346497c3c8
--- /dev/null
+++ b/products/business_intelligence/frontend/BISQLPreviewModal.tsx
@@ -0,0 +1,100 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonModal, LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+
+import { biSceneLogic } from './biSceneLogic'
+
+export function BISQLPreviewModal(): JSX.Element {
+ const {
+ sqlPreviewOpen,
+ sqlPreviewVersion,
+ sqlPreviewQuery,
+ sqlEditorUrl,
+ generatedQuery,
+ lastRunQuery,
+ displayedQueryIsCurrent,
+ } = useValues(biSceneLogic)
+ const { setSqlPreviewOpen, setSqlPreviewVersion } = useActions(biSceneLogic)
+ const source = sqlPreviewQuery?.source
+
+ return (
+ <LemonModal
+ isOpen={sqlPreviewOpen}
+ onClose={() => setSqlPreviewOpen(false)}
+ title="Worksheet SQL"
+ width={800}
+ footer={
+ <div className="flex flex-wrap justify-end gap-2">
+ <LemonButton type="secondary" onClick={() => setSqlPreviewOpen(false)}>
+ Close
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ to={sqlEditorUrl ?? undefined}
+ targetBlank
+ disabledReason={!sqlEditorUrl ? 'No query available' : undefined}
+ data-attr="bi-open-sql-editor"
+ >
+ Open in SQL editor
+ </LemonButton>
+ </div>
+ }
+ >
+ <div className="flex min-w-0 flex-col gap-3" data-attr="bi-sql-preview">
+ <LemonSegmentedButton
+ value={sqlPreviewVersion}
+ onChange={setSqlPreviewVersion}
+ options={[
+ {
+ value: 'current',
+ label: 'Current worksheet',
+ disabledReason: !generatedQuery
+ ? 'Select fields and resolve query errors first'
+ : undefined,
+ },
+ {
+ value: 'last_run',
+ label: 'Last run',
+ disabledReason: !lastRunQuery ? 'Run the worksheet first' : undefined,
+ },
+ ]}
+ />
+ {!displayedQueryIsCurrent && sqlPreviewVersion === 'current' && (
+ <LemonBanner type="info">This query includes worksheet changes that have not been run.</LemonBanner>
+ )}
+ {source ? (
+ <>
+ <CodeSnippet language={Language.SQL} wrap>
+ {source.query}
+ </CodeSnippet>
+ <p className="m-0 text-secondary">
+ Copy copies the query text. Open in SQL editor carries its connection, filters, and variable
+ values into a new tab, ready to run.
+ </p>
+ {(source.filters || source.variables || source.values) && (
+ <details>
+ <summary className="cursor-pointer">Query parameters</summary>
+ <CodeSnippet language={Language.JSON} wrap>
+ {JSON.stringify(
+ { filters: source.filters, variables: source.variables, values: source.values },
+ null,
+ 2
+ )}
+ </CodeSnippet>
+ </details>
+ )}
+ {sqlPreviewVersion === 'last_run' && (
+ <p className="m-0 text-secondary">
+ Relative dates are evaluated again when the query runs.
+ </p>
+ )}
+ </>
+ ) : (
+ <p>No query is available for this selection.</p>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
index 0fbd48fa1b81..c3ff68b368f0 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
@@ -37,7 +37,15 @@ const config: BIConfig = {
}
const tabId = 'bi-exploration-story'
-function WorksheetStage({ config, width = 1200 }: { config: BIConfig; width?: number }): JSX.Element {
+function WorksheetStage({
+ config,
+ width = 1200,
+ sqlPreview = false,
+}: {
+ config: BIConfig
+ width?: number
+ sqlPreview?: boolean
+}): JSX.Element {
useEffect(() => {
const logic = biSceneLogic({ tabId })
const unmount = logic.mount()
@@ -48,8 +56,11 @@ function WorksheetStage({ config, width = 1200 }: { config: BIConfig; width?: nu
}
logic.actions.restoreWorksheet(node)
logic.actions.recordWorksheet(true)
+ if (sqlPreview) {
+ logic.actions.setSqlPreviewOpen(true)
+ }
return unmount
- }, [config])
+ }, [config, sqlPreview])
return (
<div className="h-[850px] max-w-full" style={{ width }}>
<BusinessIntelligenceScene tabId={tabId} />
@@ -184,6 +195,7 @@ export default meta
export const FiltersAndHierarchy: StoryObj = { render: () => <WorksheetStage config={config} /> }
export const Narrow: StoryObj = { render: () => <WorksheetStage config={config} width={520} /> }
+export const SQLPreview: StoryObj = { render: () => <WorksheetStage config={config} sqlPreview /> }
const dailyConfig: BIConfig = {
...config,
chartType: ChartDisplayType.ActionsLineGraph,
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
index 08af5b6784a7..216354b6a766 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
@@ -26,6 +26,7 @@ import { getBIHierarchyParent } from './biHierarchies'
import { BIResultSummary } from './BIResultSummary'
import { keepBIScatterRows } from './biScatter'
import { biSceneLogic } from './biSceneLogic'
+import { BISQLPreviewModal } from './BISQLPreviewModal'
export const scene: SceneExport = {
component: BusinessIntelligenceScene,
@@ -57,6 +58,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
copyDisabledReason,
worksheet,
displayedQueryIsCurrent,
+ generatedQuery,
} = useValues(logic)
const {
setName,
@@ -71,6 +73,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
undo,
redo,
navigateHierarchy,
+ setSqlPreviewOpen,
} = useActions(logic)
const hierarchyParent = getBIHierarchyParent(worksheet)
@@ -100,6 +103,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
return (
<BindLogic logic={biSceneLogic} props={{ tabId }}>
<div className="flex h-full min-h-0 flex-col" data-attr="bi-worksheet">
+ <BISQLPreviewModal />
<header className="flex flex-wrap items-center gap-1 border-b px-2 py-1">
<LemonButton size="small" to={urls.businessIntelligence()}>
Worksheets
@@ -131,6 +135,15 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
</LemonButton>
<LemonMenu
items={[
+ {
+ label: 'View SQL',
+ onClick: () => setSqlPreviewOpen(true),
+ disabledReason:
+ !generatedQuery && !lastRunQuery
+ ? 'Select fields to build a query first'
+ : undefined,
+ 'data-attr': 'bi-view-sql',
+ },
{
label: 'Save a copy',
onClick: () => saveInsight({ asCopy: true }),
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index 4cf2e847a21a..427e071fd5e4 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -19,6 +19,7 @@ import { BI_EDITOR_EVENTS } from './biEditorAnalytics'
import { biEditorLogic } from './biEditorLogic'
import { BIEditorView, buildBIQuery } from './biEditorTypes'
import { biMemberAliasesLogic } from './biMemberAliasesLogic'
+import { getBIVisualizationSource } from './biQueryResults'
import { getBIScatterAxisOptions } from './biScatter'
import { biSceneLogic } from './biSceneLogic'
import { biSourcePreviewLogic } from './biSourcePreviewLogic'
@@ -575,6 +576,71 @@ describe('biSceneLogic', () => {
expect(save).not.toHaveBeenCalled()
})
+ it('previews pending or last-run SQL and carries the complete source to an unsaved SQL tab', () => {
+ const source = { table: 'events', connectionId: 'example-connection' }
+ const initial = worksheet({
+ ...config,
+ source,
+ rows: config.rows.map((field) => ({ ...field, source })),
+ columns: config.columns.map((field) => ({ ...field, source })),
+ })
+ initial.source = {
+ ...initial.source,
+ connectionId: 'example-connection',
+ filters: {
+ ...initial.source.filters,
+ properties: [
+ {
+ key: 'channel',
+ value: ['example'],
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ },
+ ],
+ },
+ variables: { example: { variableId: 'example', code_name: 'threshold', value: 10 } },
+ values: { example: 20 },
+ }
+ logic.actions.restoreWorksheet(initial)
+ logic.actions.setLastRunQuery(initial)
+ editor.actions.setLimit(100)
+ logic.actions.setSqlPreviewOpen(true)
+ expect(logic.values.sqlPreviewVersion).toBe('current')
+ expect(logic.values.displayedQueryIsCurrent).toBe(false)
+ const currentSource = getBIVisualizationSource(logic.values.worksheet)
+ expect(logic.values.sqlPreviewQuery?.source).toEqual(currentSource)
+ const handoff = (): unknown =>
+ JSON.parse(new URL(logic.values.sqlEditorUrl!, 'https://example.com').searchParams.get('open_query')!)
+ expect(handoff()).toEqual({
+ kind: NodeKind.DataVisualizationNode,
+ source: currentSource,
+ display: ChartDisplayType.ActionsTable,
+ })
+ logic.actions.setSqlPreviewVersion('last_run')
+ expect(handoff()).toEqual({
+ kind: NodeKind.DataVisualizationNode,
+ source: getBIVisualizationSource(initial),
+ display: ChartDisplayType.ActionsTable,
+ })
+ expect(logic.values.lastRunQuery).toEqual(initial)
+ expect(save).not.toHaveBeenCalled()
+ expect(exportView).not.toHaveBeenCalled()
+ })
+
+ it('clears the preview and handoff when clearing the worksheet removes its query', () => {
+ const previous = worksheet()
+ logic.actions.restoreWorksheet(previous)
+ logic.actions.setLastRunQuery(previous)
+ logic.actions.setSqlPreviewOpen(true)
+ expect(logic.values.sqlEditorUrl).not.toBeNull()
+ editor.actions.resetConfig()
+ expect(logic.values.sqlPreviewOpen).toBe(false)
+ logic.actions.setSqlPreviewVersion('current')
+ expect(logic.values.sqlEditorUrl).toBeNull()
+ logic.actions.setSqlPreviewVersion('last_run')
+ expect(logic.values.sqlEditorUrl).toBeNull()
+ })
+
it('undoes shelves, filters, calculations and formatting without running a query, and branches after undo', async () => {
await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
const snapshots = [JSON.parse(JSON.stringify(logic.values.worksheet))]
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index 2cac561f06c4..62e09e9140bd 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -58,6 +58,7 @@ import {
import type { BIQueryBuildResult } from './biEditorTypes'
import { mergeBITableSettings } from './biMeasureSettings'
import { applyBIDateRange, mergeBIQuerySource } from './biQueryFilters'
+import { getBIVisualizationSource } from './biQueryResults'
import { getBIScatterAxisOptions } from './biScatter'
export interface BISceneLogicProps {
@@ -111,6 +112,10 @@ export interface biSceneLogicValues {
loadError: string | null
name: string
saveDisabledReason: string | undefined
+ sqlEditorUrl: string | null
+ sqlPreviewOpen: boolean
+ sqlPreviewQuery: BIVisualizationNode | null
+ sqlPreviewVersion: 'current' | 'last_run'
visualization: BIVisualizationNode
worksheet: BIVisualizationNode
}
@@ -245,6 +250,12 @@ export interface biSceneLogicActions {
axis: 'x' | 'y'
column: string
}
+ setSqlPreviewOpen: (open: boolean) => {
+ open: boolean
+ }
+ setSqlPreviewVersion: (version: 'current' | 'last_run') => {
+ version: 'current' | 'last_run'
+ }
setVisualization: (visualization: VisualizationNode) => {
visualization: VisualizationNode
}
@@ -263,6 +274,12 @@ export interface biSceneLogicActions {
export interface biSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ sqlPreviewQuery: (
+ sqlPreviewVersion: 'current' | 'last_run',
+ worksheet: BIVisualizationNode,
+ lastRunQuery: BIVisualizationNode | null
+ ) => BIVisualizationNode | null
+ sqlEditorUrl: (sqlPreviewQuery: BIVisualizationNode | null) => string | null
displayedQueryIsCurrent: (lastRunQuery: BIVisualizationNode | null, worksheet: BIVisualizationNode) => boolean
canUndo: (history: BIWorksheetHistory) => boolean
canRedo: (history: BIWorksheetHistory) => boolean
@@ -331,6 +348,8 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
selectConnection: (connectionId: string | null) => ({ connectionId }),
setExportViewName: (name: string) => ({ name }),
setExportViewOpen: (open: boolean) => ({ open }),
+ setSqlPreviewOpen: (open: boolean) => ({ open }),
+ setSqlPreviewVersion: (version: 'current' | 'last_run') => ({ version }),
}),
loaders(({ values, actions }) => ({
insight: [
@@ -462,8 +481,34 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
],
exportViewName: ['', { setExportViewName: (_, { name }) => name }],
exportViewOpen: [false, { setExportViewOpen: (_, { open }) => open }],
+ sqlPreviewOpen: [false, { setSqlPreviewOpen: (_, { open }) => open, restoreWorksheet: () => false }],
+ sqlPreviewVersion: ['current' as 'current' | 'last_run', { setSqlPreviewVersion: (_, { version }) => version }],
}),
selectors({
+ sqlPreviewQuery: [
+ (s) => [s.sqlPreviewVersion, s.worksheet, s.lastRunQuery],
+ (
+ version: 'current' | 'last_run',
+ worksheet: BIVisualizationNode,
+ lastRun: BIVisualizationNode | null
+ ): BIVisualizationNode | null => {
+ const query = version === 'current' ? worksheet : lastRun
+ return query?.source.query ? { ...query, source: getBIVisualizationSource(query) } : null
+ },
+ ],
+ sqlEditorUrl: [
+ (s) => [s.sqlPreviewQuery],
+ (query: BIVisualizationNode | null): string | null =>
+ query
+ ? urls.sqlEditor({
+ query: {
+ kind: NodeKind.DataVisualizationNode,
+ source: query.source,
+ display: ChartDisplayType.ActionsTable,
+ },
+ })
+ : null,
+ ],
displayedQueryIsCurrent: [
(s) => [s.lastRunQuery, s.worksheet],
(lastRunQuery: BIVisualizationNode | null, worksheet: BIVisualizationNode): boolean =>
@@ -548,6 +593,11 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
],
}),
listeners(({ actions, values, props, cache }) => ({
+ setSqlPreviewOpen: ({ open }) => {
+ if (open) {
+ actions.setSqlPreviewVersion(values.generatedQuery ? 'current' : 'last_run')
+ }
+ },
recordWorksheet: ({ reset }) => {
if (!cache.restoringHistory) {
actions.pushHistory(