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(sql-editor): add BI query builder (#77479)

Marius Andrad140943100e7
diff --git a/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.test.ts b/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.test.ts
index a25245c42250..6e677fa8ba20 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.test.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.test.ts
@@ -20,6 +20,9 @@ jest.mock('lib/api', () => ({
get: jest.fn(),
update: jest.fn(),
create: jest.fn(),
+ recordings: {
+ listPlaylists: jest.fn(),
+ },
},
}))
@@ -40,8 +43,16 @@ describe('sidePanelLogic', () => {
beforeEach(async () => {
initKeaTests()
- ;(api.get as jest.Mock).mockResolvedValue({ tabs: [], homepage: null })
+ ;(api.get as jest.Mock).mockResolvedValue({
+ tabs: [],
+ homepage: null,
+ count: 0,
+ next: null,
+ previous: null,
+ results: [],
+ })
;(api.update as jest.Mock).mockResolvedValue({ tabs: [], homepage: null })
+ ;(api.recordings.listPlaylists as jest.Mock).mockResolvedValue({ results: [], count: 0, filters: null })
await expectLogic(teamLogic).toDispatchActions(['loadCurrentTeamSuccess'])
featureFlagLogic.mount()
sceneLogic.build({ scenes: testScenes }).mount()
diff --git a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
index 88b55fc40df7..33dbdd737afc 100644
--- a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
+++ b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
@@ -100,6 +100,7 @@ export const DatabaseTree = memo(function DatabaseTree({
<QueryDatabase
virtualizationScrollContainerRef={scrollContainerRef}
extraTreeSections={extraTreeSections}
+ tabId={tabId}
/>
</div>
<SyncMoreNotice />
diff --git a/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx b/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx
index ebccce3ee144..210b232450e6 100644
--- a/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx
+++ b/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx
@@ -1,9 +1,11 @@
import clsx from 'clsx'
+import type { ReactNode } from 'react'
import { useState } from 'react'
import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'
import { NodeKind } from '~/queries/schema/schema-general'
+import { escapeDottedHogQLIdentifier } from '~/queries/utils'
import { HogQLEditor } from '../HogQLEditor/HogQLEditor'
@@ -14,15 +16,34 @@ export const HogQLDropdown = ({
hogQLEditorPlaceholder,
className = '',
size,
+ connectionId,
+ buttonIcon,
+ buttonLabel,
+ buttonTooltip,
+ buttonAriaLabel,
+ visible,
+ onVisibilityChange,
}: {
hogQLValue: string
tableName: string
+ connectionId?: string
className?: string
hogQLEditorPlaceholder?: string
size?: 'small' | 'medium'
+ buttonIcon?: JSX.Element
+ buttonLabel?: ReactNode
+ buttonTooltip?: string
+ buttonAriaLabel?: string
+ visible?: boolean
+ onVisibilityChange?: (visible: boolean) => void
onHogQLValueChange: (hogQLValue: string) => void
}): JSX.Element => {
- const [isHogQLDropdownVisible, setIsHogQLDropdownVisible] = useState(false)
+ const [internalVisibility, setInternalVisibility] = useState(false)
+ const isHogQLDropdownVisible = visible ?? internalVisibility
+ const setIsHogQLDropdownVisible = (nextVisibility: boolean): void => {
+ setInternalVisibility(nextVisibility)
+ onVisibilityChange?.(nextVisibility)
+ }
return (
<div className={clsx('flex-auto min-w-0', className)}>
@@ -35,7 +56,11 @@ export const HogQLDropdown = ({
<div className="w-120" style={{ maxWidth: 'max(60vw, 20rem)' }}>
<HogQLEditor
value={hogQLValue}
- metadataSource={{ kind: NodeKind.HogQLQuery, query: `SELECT * FROM ${tableName}` }}
+ metadataSource={{
+ kind: NodeKind.HogQLQuery,
+ query: `SELECT * FROM ${escapeDottedHogQLIdentifier(tableName)}`,
+ connectionId,
+ }}
onChange={(currentValue) => {
onHogQLValueChange(currentValue)
setIsHogQLDropdownVisible(false)
@@ -49,9 +74,12 @@ export const HogQLDropdown = ({
fullWidth
type="secondary"
size={size}
+ icon={buttonIcon}
+ tooltip={buttonTooltip}
+ aria-label={buttonAriaLabel}
onClick={() => setIsHogQLDropdownVisible(!isHogQLDropdownVisible)}
>
- <code>{hogQLValue}</code>
+ {buttonLabel ?? <code>{hogQLValue}</code>}
</LemonButton>
</LemonDropdown>
</div>
diff --git a/frontend/src/lib/components/HogQLEditor/HogQLEditor.test.tsx b/frontend/src/lib/components/HogQLEditor/HogQLEditor.test.tsx
new file mode 100644
index 000000000000..908f31c72e14
--- /dev/null
+++ b/frontend/src/lib/components/HogQLEditor/HogQLEditor.test.tsx
@@ -0,0 +1,32 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+
+import { HogQLEditor } from './HogQLEditor'
+
+jest.mock('lib/monaco/CodeEditorInline', () => ({
+ CodeEditorInline: ({
+ onChange,
+ onPressCmdEnter,
+ }: {
+ onChange: (value: string) => void
+ onPressCmdEnter?: (value: string, selectionType: 'selection' | 'full') => void
+ }): JSX.Element => (
+ <>
+ <textarea aria-label="HogQL expression" onChange={(event) => onChange(event.target.value)} />
+ <button onClick={() => onPressCmdEnter?.('', 'selection')}>Submit with shortcut</button>
+ </>
+ ),
+}))
+
+describe('HogQLEditor', () => {
+ it('submits the full buffered expression with Cmd+Enter when Monaco has an empty selection', () => {
+ const onChange = jest.fn()
+ render(<HogQLEditor value="" onChange={onChange} />)
+
+ fireEvent.change(screen.getByLabelText('HogQL expression'), {
+ target: { value: 'properties.$browser' },
+ })
+ fireEvent.click(screen.getByText('Submit with shortcut'))
+
+ expect(onChange).toHaveBeenCalledWith('properties.$browser')
+ })
+})
diff --git a/frontend/src/lib/components/HogQLEditor/HogQLEditor.tsx b/frontend/src/lib/components/HogQLEditor/HogQLEditor.tsx
index 37eaaa63cab4..becd58bde37e 100644
--- a/frontend/src/lib/components/HogQLEditor/HogQLEditor.tsx
+++ b/frontend/src/lib/components/HogQLEditor/HogQLEditor.tsx
@@ -76,8 +76,8 @@ export function HogQLEditor({
onPressCmdEnter={
disableCmdEnter
? undefined
- : (value) => {
- onChange(value)
+ : () => {
+ onChange(bufferedValue)
}
}
/>
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6a4854d4c205..0d3ea07a1944 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -484,6 +484,7 @@ export const FEATURE_FLAGS = {
SHOW_REPLAY_FILTERS_FEEDBACK_BUTTON: 'show-replay-filters-feedback-button', // owner: @ksvat #team-replay
SIGNUP_AA_TEST_4_WAY: 'signup-aa-test-4-way', // owner: @andehen #team-experiments multivariate=control,test-1,test-2,test-3
SLACK_DWH: 'slack-dwh', // owner: @MarconLP #team-warehouse-sources
+ SQL_EDITOR_BI_MODE: 'sql-editor-bi-mode', // owner: @mariusandra #team-data-tools
SQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeus
SQL_INSIGHT_DATE_FILTER_NOTICE: 'sql-insight-date-filter-notice', // owner: #team-product-analytics, gates the notice on SQL insights affected by the date filter resolution fix
SSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platform
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx
index 7cd630c17c27..b3bab67b576e 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx
@@ -140,6 +140,52 @@ describe('LemonTree virtualization', () => {
expect(document.activeElement).toBe(grandchild)
})
+ it('scrolls an imperatively focused item to the top third after its folder expands', async () => {
+ const treeRef = createRef<LemonTreeRef>()
+ const data: TreeDataItem[] = [
+ {
+ id: 'root',
+ name: 'root',
+ children: [{ id: 'target', name: 'target' }],
+ },
+ ]
+ const boundsSpy = jest
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: HTMLElement) {
+ const element = this
+ const top = element.dataset.id === 'target' ? 260 : 0
+ const height = element.dataset.id === 'target' ? 31 : 300
+ return {
+ x: 0,
+ y: top,
+ top,
+ bottom: top + height,
+ left: 0,
+ right: 100,
+ width: 100,
+ height,
+ toJSON: () => ({}),
+ }
+ })
+
+ const { container, rerender } = render(<LemonTree ref={treeRef} data={data} expandedItemIds={[]} />)
+ const viewport = setViewportHeight(container, 300)
+ const scrollTo = jest.fn()
+ Object.defineProperty(viewport, 'scrollTo', { value: scrollTo, configurable: true })
+
+ act(() => {
+ treeRef.current?.focusItem('target', { scrollPosition: 'top-third', behavior: 'smooth' })
+ })
+ rerender(<LemonTree ref={treeRef} data={data} expandedItemIds={['root']} />)
+
+ await waitFor(() => {
+ expect(scrollTo).toHaveBeenCalledWith({ top: 160, behavior: 'smooth' })
+ })
+ expect(document.activeElement).toBe(screen.getByLabelText('tree item: target'))
+
+ boundsSpy.mockRestore()
+ })
+
it('virtualizes against an outer scroll container when provided', async () => {
const outerScrollRef = createRef<HTMLDivElement>()
const data: TreeDataItem[] = [
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
index 48678f560d75..4bf742761399 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
@@ -222,7 +222,12 @@ export type LemonTreeNodeProps = LemonTreeBaseProps & {
export interface LemonTreeRef {
getVisibleItems: () => TreeDataItem[]
- focusItem: (id: string) => void
+ focusItem: (id: string, options?: LemonTreeFocusOptions) => void
+}
+
+export interface LemonTreeFocusOptions {
+ scrollPosition?: 'top-third'
+ behavior?: ScrollBehavior
}
type FlattenedTreeItem = {
@@ -721,6 +726,10 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
const [disableKeyboardInput, setDisableKeyboardInput] = useState(false)
const [typeAheadBuffer, setTypeAheadBuffer] = useState<string>('')
const [focusedItemId, setFocusedItemId] = useState<string | undefined>(defaultSelectedFolderOrNodeId)
+ const [imperativeFocusRequest, setImperativeFocusRequest] = useState<{
+ id: string
+ options: LemonTreeFocusOptions
+ } | null>(null)
const [virtualWindow, setVirtualWindow] = useState<VirtualWindow>({
startIndex: 0,
endIndex: 0,
@@ -878,11 +887,11 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
return []
}, [])
- const focusTreeItem = useCallback((id: string): void => {
+ const focusTreeItem = useCallback((id: string, preventScroll = false): void => {
setFocusedItemId(id)
setTimeout(() => {
const element = containerRef.current?.querySelector(`[data-id="${CSS.escape(id)}"]`) as HTMLElement
- element?.focus()
+ element?.focus({ preventScroll })
}, 0)
}, [])
@@ -1335,8 +1344,9 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
useImperativeHandle(ref, () => ({
getVisibleItems,
- focusItem: (id: string) => {
- focusTreeItem(id)
+ focusItem: (id: string, options: LemonTreeFocusOptions = {}) => {
+ focusTreeItem(id, !!options.scrollPosition)
+ setImperativeFocusRequest({ id, options })
},
}))
@@ -1462,6 +1472,43 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
}
}, [computeVirtualWindow, focusedItemId, flattenedVisibleItems.length])
+ useEffect(() => {
+ if (!imperativeFocusRequest || (isFinishedBuildingTreeData ?? true) === false) {
+ return
+ }
+
+ const element = containerRef.current?.querySelector(
+ `[data-id="${CSS.escape(imperativeFocusRequest.id)}"]`
+ ) as HTMLElement | null
+ if (!element) {
+ return
+ }
+
+ element.focus({ preventScroll: !!imperativeFocusRequest.options.scrollPosition })
+
+ if (imperativeFocusRequest.options.scrollPosition === 'top-third') {
+ const viewport = virtualizationScrollContainerRef?.current ?? scrollViewportRef.current
+ if (viewport) {
+ const viewportBounds = viewport.getBoundingClientRect()
+ const elementBounds = element.getBoundingClientRect()
+ const top = Math.max(
+ 0,
+ viewport.scrollTop + elementBounds.top - viewportBounds.top - viewport.clientHeight / 3
+ )
+ viewport.scrollTo({ top, behavior: imperativeFocusRequest.options.behavior ?? 'auto' })
+ }
+ }
+
+ setImperativeFocusRequest(null)
+ }, [
+ imperativeFocusRequest,
+ isFinishedBuildingTreeData,
+ virtualizationScrollContainerRef,
+ virtualWindow.endIndex,
+ virtualWindow.startIndex,
+ expandedItemIdsState,
+ ])
+
const virtualizedStartIndex = virtualWindow.startIndex
const virtualizedEndIndex = virtualWindow.endIndex
const indexByItemId = useMemo(
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 7fc043c40d62..133a28e7ee82 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -578,10 +578,11 @@ function OutputActions({
interface OutputPaneProps {
tabId: string
showToolbar?: boolean
+ biMode?: boolean
onShareTab?: () => void
}
-export function OutputPane({ tabId, showToolbar = true, onShareTab }: OutputPaneProps): JSX.Element {
+export function OutputPane({ tabId, showToolbar = true, biMode = false, onShareTab }: OutputPaneProps): JSX.Element {
const { activeTab } = useValues(outputPaneLogic)
const { setActiveTab } = useActions(outputPaneLogic)
@@ -600,7 +601,7 @@ export function OutputPane({ tabId, showToolbar = true, onShareTab }: OutputPane
const response = dataNodeResponse as HogQLQueryResponse | undefined
const splitPaneRef = useRef<HTMLDivElement>(null)
- const splitView = activeTab === OutputTab.Both
+ const splitView = !biMode && activeTab === OutputTab.Both
const splitResizerProps = useMemo<ResizerLogicProps>(
() => ({
containerRef: splitPaneRef,
@@ -806,7 +807,23 @@ export function OutputPane({ tabId, showToolbar = true, onShareTab }: OutputPane
onToggleChartSettingsPanel: toggleVisualizationSettingsPanel,
}
- const outputContent = splitView ? (
+ const outputContent = biMode ? (
+ <div className="relative flex flex-1 min-h-0 bg-dark">
+ {showToolbar ? (
+ <LemonButton
+ className="absolute right-2 top-2 z-10"
+ disabledReason={!hasColumns ? 'No results to visualize' : undefined}
+ type={isChartSettingsPanelOpen ? 'primary' : 'secondary'}
+ icon={<IconGear />}
+ size="small"
+ onClick={toggleVisualizationSettingsPanel}
+ tooltip="Visualization settings"
+ data-attr="sql-editor-visualization-settings-button"
+ />
+ ) : null}
+ <Content activeTab={OutputTab.Visualization} {...sharedContentProps} />
+ </div>
+ ) : splitView ? (
<div className="flex flex-1 min-h-0 bg-dark">
<div
ref={splitPaneRef}
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index 789e57d841fa..070d79a734f4 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -14,6 +14,7 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconCancel } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonMenu } from 'lib/lemon-ui/LemonMenu/LemonMenu'
+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { userPreferencesLogic } from 'lib/logic/userPreferencesLogic'
@@ -28,6 +29,9 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+import { BIEditor } from './bi/BIEditor'
+import { biEditorLogic } from './bi/biEditorLogic'
+import { BIEditorView } from './bi/biEditorTypes'
import { FixErrorButton } from './components/FixErrorButton'
import { ConnectionSelector } from './ConnectionSelector'
import { editorSizingLogic } from './editorSizingLogic'
@@ -79,6 +83,7 @@ export function QueryWindow({
}: QueryWindowProps): JSX.Element {
const codeEditorKey = `hogql-editor-${tabId}`
const logic = sqlEditorLogic({ tabId })
+ const biLogic = biEditorLogic({ tabId })
const {
queryInput,
@@ -92,6 +97,7 @@ export function QueryWindow({
sendRawQueryEnabled,
selectedConnectionSupportsHogQL,
} = useValues(logic)
+ const { config: biConfig, editorView } = useValues(biLogic)
const {
setQueryInput,
@@ -104,14 +110,17 @@ export function QueryWindow({
openMaterializationModal,
setSourceQuery,
} = useActions(logic)
+ const { setEditorView } = useActions(biLogic)
const { setSuggestedQueryInput, reportAIQueryPromptOpen } = useActions(logic)
+ const biModeFeatureEnabled = useFeatureFlag('SQL_EDITOR_BI_MODE')
const vimModeFeatureEnabled = useFeatureFlag('SQL_EDITOR_VIM_MODE')
const { editorVimModeEnabled } = useValues(userPreferencesLogic)
const { setEditorVimModeEnabled } = useActions(userPreferencesLogic)
const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)
// Raw-only connections are forced to raw SQL mode — no toggle to show.
const canSendRawQuery = !!selectedConnectionId && selectedConnectionSupportsHogQL
+ const showBIEditor = biModeFeatureEnabled && mode === SQLEditorMode.FullScene && editorView === BIEditorView.BI
const debouncedMaxToolQueryInput = useDebouncedValue(queryInput, EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS)
const debouncedMaxToolSourceQuery = useDebouncedValue(sourceQuery, EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS)
const executeSqlToolStateRef = useRef({ queryInput, sourceQuery })
@@ -254,21 +263,39 @@ export function QueryWindow({
showDatabaseTree={showDatabaseTree}
onShowDatabaseTree={onShowDatabaseTree}
/>
+ {mode === SQLEditorMode.FullScene && biModeFeatureEnabled ? (
+ <LemonSegmentedButton
+ value={editorView}
+ onChange={setEditorView}
+ options={[
+ { value: BIEditorView.SQL, label: 'SQL' },
+ { value: BIEditorView.BI, label: 'BI' },
+ ]}
+ size="small"
+ />
+ ) : null}
<RunButton
onRunQuery={onRunQuery}
runQueryLoading={runQueryLoading}
- runQueryDisabledReason={runQueryDisabledReason}
+ runQueryDisabledReason={
+ runQueryDisabledReason ??
+ (showBIEditor && !biConfig.source
+ ? 'Drag a field into the BI editor before running'
+ : undefined)
+ }
runQueryTooltip={runQueryTooltip}
onCancelQuery={onCancelQuery}
cancelQueryLoading={cancelQueryLoading}
/>
<CollapsedConnectionSelector tabId={tabId} mode={mode} />
- <LemonDivider vertical />
- <QueryVariablesMenu
- disabledReason={editingView ? 'Variables are not allowed in views.' : undefined}
- />
- <QueryFiltersMenu />
- {editingView ? (
+ {!showBIEditor ? <LemonDivider vertical /> : null}
+ {!showBIEditor ? (
+ <QueryVariablesMenu
+ disabledReason={editingView ? 'Variables are not allowed in views.' : undefined}
+ />
+ ) : null}
+ {!showBIEditor ? <QueryFiltersMenu /> : null}
+ {editingView && !showBIEditor ? (
<AccessControlAction
resourceType={AccessControlResourceType.WarehouseObjects}
minAccessLevel={AccessControlLevel.Editor}
@@ -309,7 +336,9 @@ export function QueryWindow({
</div>
) : null}
- {showQueryPanel ? (
+ {showQueryPanel && showBIEditor ? <BIEditor tabId={tabId} /> : null}
+
+ {showQueryPanel && !showBIEditor ? (
<QueryPane
originalValue={originalQueryInput ?? ''}
queryInput={(suggestedQueryInput || queryInput) ?? ''}
@@ -367,7 +396,9 @@ export function QueryWindow({
/>
) : null}
- {showOutputPanel ? <InternalQueryWindow tabId={tabId} onShareTab={onShareTab} /> : null}
+ {showOutputPanel ? (
+ <InternalQueryWindow tabId={tabId} biMode={showBIEditor} onShareTab={onShareTab} />
+ ) : null}
</div>
)
}
@@ -532,9 +563,11 @@ function RunButton({
const InternalQueryWindow = memo(function InternalQueryWindow({
tabId,
+ biMode,
onShareTab,
}: {
tabId: string
+ biMode: boolean
onShareTab?: () => void
}): JSX.Element | null {
const { finishedLoading } = useValues(sqlEditorLogic)
@@ -543,7 +576,7 @@ const InternalQueryWindow = memo(function InternalQueryWindow({
return null
}
- return <OutputPane tabId={tabId} onShareTab={onShareTab} />
+ return <OutputPane tabId={tabId} biMode={biMode} onShareTab={onShareTab} />
})
function CollapsedConnectionSelector({ tabId, mode }: { tabId: string; mode?: SQLEditorMode }): JSX.Element | null {
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index cd73069039f4..aaf6fb1d80b4 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -99,6 +99,7 @@ export function SQLEditor({
const ref = useRef(null)
const navigatorRef = useRef(null)
const queryPaneRef = useRef(null)
+ const biEditorRef = useRef(null)
const sidebarRef = useRef(null)
const databaseTreeRef = useRef(null)
const [hasShownDatabaseTree, setHasShownDatabaseTree] = useState(defaultShowDatabaseTree)
@@ -123,6 +124,13 @@ export function SQLEditor({
sidebarRef,
databaseTreeRef,
queryPaneDefaultHeight,
+ biEditorResizerProps: {
+ containerRef: biEditorRef,
+ logicKey: 'bi-editor-pane',
+ placement: 'bottom' as const,
+ persistent: true,
+ persistPrefix: 'v1',
+ },
sourceNavigatorResizerProps: {
containerRef: navigatorRef,
logicKey: resizerKey('source-navigator'),
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx
new file mode 100644
index 000000000000..1079b9055cfa
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx
@@ -0,0 +1,647 @@
+import { useActions, useValues } from 'kea'
+import type { DragEvent, ReactNode } from 'react'
+
+import {
+ IconCalculator,
+ IconDatabase,
+ IconFilter,
+ IconGraph,
+ IconLifecycle,
+ IconMagicWand,
+ IconPencil,
+ IconPieChart,
+ IconPlus,
+ IconTrends,
+ IconX,
+} from '@posthog/icons'
+import { LemonButton, LemonCard, LemonInput, LemonLabel, LemonSearchableSelect, LemonSelect } from '@posthog/lemon-ui'
+
+import { HogQLDropdown } from 'lib/components/HogQLDropdown/HogQLDropdown'
+import { Resizer } from 'lib/components/Resizer/Resizer'
+import { dayjs } from 'lib/dayjs'
+import { Icon123, IconAreaChart, IconHeatmap, IconTableChart } from 'lib/lemon-ui/icons'
+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
+import { cn } from 'lib/utils/css-classes'
+
+import { ChartDisplayType } from '~/types'
+
+import { editorSizingLogic } from '../editorSizingLogic'
+import { queryDatabaseLogic } from '../sidebar/queryDatabaseLogic'
+import { biEditorLogic } from './biEditorLogic'
+import {
+ BIAggregation,
+ BIDateBucket,
+ BI_FIELD_DRAG_MIME_TYPE,
+ BIFilterOperator,
+ BIShelf,
+ BIField,
+ getBIDataSourceKey,
+ isDateTimeBIField,
+ isNumericBIField,
+ parseBIField,
+} from './biEditorTypes'
+
+const CHART_TYPE_OPTIONS: { value: ChartDisplayType; label: string; icon: JSX.Element }[] = [
+ { value: ChartDisplayType.Auto, label: 'Auto', icon: <IconMagicWand /> },
+ { value: ChartDisplayType.ActionsTable, label: 'Table', icon: <IconTableChart /> },
+ { value: ChartDisplayType.ActionsLineGraph, label: 'Line chart', icon: <IconTrends /> },
+ { value: ChartDisplayType.ActionsBar, label: 'Bar chart', icon: <IconGraph /> },
+ { value: ChartDisplayType.ActionsStackedBar, label: 'Stacked bar chart', icon: <IconLifecycle /> },
+ { value: ChartDisplayType.ActionsAreaGraph, label: 'Area chart', icon: <IconAreaChart /> },
+ { value: ChartDisplayType.ActionsPie, label: 'Pie chart', icon: <IconPieChart /> },
+ { value: ChartDisplayType.TwoDimensionalHeatmap, label: '2D heatmap', icon: <IconHeatmap /> },
+ { value: ChartDisplayType.BoldNumber, label: 'Big number', icon: <Icon123 /> },
+]
+
+const AGGREGATION_OPTIONS: { value: BIAggregation; label: string }[] = [
+ { value: 'custom', label: 'SQL expression' },
+ { value: 'count', label: 'Count' },
+ { value: 'count_distinct', label: 'Count distinct' },
+ { value: 'sum', label: 'Sum' },
+ { value: 'average', label: 'Average' },
+ { value: 'minimum', label: 'Minimum' },
+ { value: 'maximum', label: 'Maximum' },
+]
+
+const FILTER_OPERATOR_OPTIONS: { value: BIFilterOperator; label: string }[] = [
+ { value: 'equals', label: 'Equals' },
+ { value: 'not_equals', label: 'Does not equal' },
+ { value: 'contains', label: 'Contains' },
+ { value: 'greater_than', label: 'Greater than' },
+ { value: 'less_than', label: 'Less than' },
+ { value: 'last_7_days', label: 'Last 7 days' },
+ { value: 'is_set', label: 'Is set' },
+ { value: 'is_not_set', label: 'Is not set' },
+ { value: 'custom', label: 'SQL condition' },
+]
+
+const DATE_BUCKET_OPTIONS: { value: BIDateBucket | null; label: string }[] = [
+ { value: null, label: 'Exact' },
+ { value: 'minute', label: 'Minute' },
+ { value: 'hour', label: 'Hour' },
+ { value: 'day', label: 'Day' },
+ { value: 'week', label: 'Week' },
+ { value: 'month', label: 'Month' },
+ { value: 'quarter', label: 'Quarter' },
+ { value: 'year', label: 'Year' },
+]
+
+export function BIEditor({ tabId }: { tabId: string }): JSX.Element {
+ const logic = biEditorLogic({ tabId })
+ const { activeDropShelf, activeExpressionEditorId, availableDataSources, config, databaseLoading } =
+ useValues(logic)
+ const { biEditorHeight, biEditorResizerProps } = useValues(editorSizingLogic)
+ const { setDatabaseTreeCollapsed } = useActions(editorSizingLogic)
+ const { locateTable } = useActions(queryDatabaseLogic)
+ const {
+ addBlankFieldToShelf,
+ addFieldToShelf,
+ clearActiveDropShelf,
+ removeFieldFromShelf,
+ resetConfig,
+ setActiveDropShelf,
+ setActiveExpressionEditorId,
+ setChartType,
+ setDataSource,
+ setFieldDateBucket,
+ setFieldExpression,
+ setFilterCustomExpression,
+ setFilterOperator,
+ setFilterValue,
+ setValueAggregation,
+ setValueCustomExpression,
+ } = useActions(logic)
+
+ return (
+ <div
+ className="relative flex min-h-44 shrink-0 flex-col gap-3 overflow-hidden border-b bg-primary p-3"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: `${biEditorHeight}px`, maxHeight: 'calc(100% - 10rem)' }}
+ ref={biEditorResizerProps.containerRef}
+ >
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex items-center gap-1">
+ <LemonLabel info="Fields are limited to this table and its related folders.">
+ Data source
+ </LemonLabel>
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ disabledReason={!config.source ? 'Select a data source first' : undefined}
+ onClick={() => {
+ if (config.source) {
+ setDatabaseTreeCollapsed(false)
+ locateTable(config.source.table)
+ }
+ }}
+ >
+ Locate
+ </LemonButton>
+ </div>
+ <div className="flex items-center gap-2">
+ <LemonSearchableSelect
+ value={config.source ? getBIDataSourceKey(config.source) : undefined}
+ options={availableDataSources.map((source) => ({
+ value: getBIDataSourceKey(source),
+ label: source.table,
+ }))}
+ onSelect={(sourceKey) => {
+ const source = availableDataSources.find(
+ (candidate) => getBIDataSourceKey(candidate) === sourceKey
+ )
+ if (source) {
+ setDataSource(source)
+ }
+ }}
+ icon={<IconDatabase />}
+ loading={databaseLoading}
+ disabledReason={
+ !databaseLoading && availableDataSources.length === 0
+ ? 'No tables available for this connection'
+ : undefined
+ }
+ placeholder="Select a table"
+ searchPlaceholder="Search tables"
+ searchInputDataAttr="bi-editor-data-source-search"
+ noResultsMessage="No matching tables"
+ size="small"
+ className="min-w-64 max-w-120"
+ truncateText={{ maxWidthClass: 'max-w-96' }}
+ dropdownMaxContentWidth
+ data-attr="bi-editor-data-source"
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={resetConfig}
+ disabledReason={!config.source ? 'No BI setup to clear' : undefined}
+ >
+ Clear
+ </LemonButton>
+ </div>
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Chart type</LemonLabel>
+ <div className="flex flex-wrap gap-1" role="group" aria-label="Chart type">
+ {CHART_TYPE_OPTIONS.map((option) => (
+ <LemonButton
+ key={option.value}
+ type={config.chartType === option.value ? 'primary' : 'secondary'}
+ active={config.chartType === option.value}
+ icon={option.icon}
+ size="small"
+ tooltip={option.label}
+ aria-label={option.label}
+ data-attr={`bi-editor-chart-type-${option.value}`}
+ onClick={() => setChartType(option.value)}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+
+ <div className="grid min-h-0 flex-1 grid-cols-1 gap-3 overflow-auto lg:grid-cols-2">
+ <Shelf
+ shelf="rows"
+ title="Rows"
+ description="Group results by these fields"
+ icon={<IconTableChart />}
+ itemCount={config.rows.length}
+ isActiveDropTarget={activeDropShelf === 'rows'}
+ onDropField={addFieldToShelf}
+ onActiveDropTargetChange={(active) =>
+ active ? setActiveDropShelf('rows') : clearActiveDropShelf('rows')
+ }
+ onAddField={() => addBlankFieldToShelf('rows')}
+ addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}
+ >
+ {config.rows.map((field, index) => (
+ <FieldExpressionEditor
+ key={field.id}
+ field={field}
+ autoOpen={activeExpressionEditorId === field.id}
+ onAutoOpenClose={() => setActiveExpressionEditorId(null)}
+ onChange={(expression) => setFieldExpression('rows', index, expression)}
+ onDateBucketChange={(dateBucket) => setFieldDateBucket('rows', index, dateBucket)}
+ onRemove={() => removeFieldFromShelf('rows', index)}
+ />
+ ))}
+ </Shelf>
+
+ <Shelf
+ shelf="columns"
+ title="Columns"
+ description="Add a second grouping for charts that use one"
+ icon={<IconTableChart />}
+ itemCount={config.columns.length}
+ isActiveDropTarget={activeDropShelf === 'columns'}
+ onDropField={addFieldToShelf}
+ onActiveDropTargetChange={(active) =>
+ active ? setActiveDropShelf('columns') : clearActiveDropShelf('columns')
+ }
+ onAddField={() => addBlankFieldToShelf('columns')}
+ addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}
+ >
+ {config.columns.map((field, index) => (
+ <FieldExpressionEditor
+ key={field.id}
+ field={field}
+ autoOpen={activeExpressionEditorId === field.id}
+ onAutoOpenClose={() => setActiveExpressionEditorId(null)}
+ onChange={(expression) => setFieldExpression('columns', index, expression)}
+ onDateBucketChange={(dateBucket) => setFieldDateBucket('columns', index, dateBucket)}
+ onRemove={() => removeFieldFromShelf('columns', index)}
+ />
+ ))}
+ </Shelf>
+
+ <Shelf
+ shelf="values"
+ title="Values"
+ description="Calculate the values shown in the chart"
+ icon={<IconCalculator />}
+ itemCount={config.values.length}
+ isActiveDropTarget={activeDropShelf === 'values'}
+ onDropField={addFieldToShelf}
+ onActiveDropTargetChange={(active) =>
+ active ? setActiveDropShelf('values') : clearActiveDropShelf('values')
+ }
+ onAddField={() => addBlankFieldToShelf('values')}
+ addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}
+ >
+ {config.values.map((value, index) => (
+ <div
+ key={`${value.field.id}-${index}`}
+ className="flex w-full min-w-0 items-center gap-2 rounded"
+ >
+ <LemonSelect
+ value={value.aggregation}
+ options={AGGREGATION_OPTIONS.map((option) => ({
+ ...option,
+ disabledReason:
+ !isNumericBIField(value.field) &&
+ ['sum', 'average', 'minimum', 'maximum'].includes(option.value)
+ ? 'This calculation requires a numeric field'
+ : undefined,
+ }))}
+ onChange={(aggregation) => setValueAggregation(index, aggregation)}
+ size="xsmall"
+ dropdownMatchSelectWidth={false}
+ />
+ <ExpressionEditorButton
+ value={value.field.expression}
+ field={value.field}
+ label="Edit field expression"
+ emptyLabel="Select field"
+ visible={activeExpressionEditorId === value.field.id ? true : undefined}
+ onVisibilityChange={(visible) => {
+ if (!visible) {
+ setActiveExpressionEditorId(null)
+ }
+ }}
+ onChange={(expression) => setFieldExpression('values', index, expression)}
+ />
+ <DateBucketSelect
+ field={value.field}
+ onChange={(dateBucket) => setFieldDateBucket('values', index, dateBucket)}
+ />
+ {value.aggregation === 'custom' ? (
+ <ExpressionEditorButton
+ value={value.customExpression ?? ''}
+ field={value.field}
+ label={
+ value.customExpression
+ ? 'Edit aggregation SQL expression'
+ : 'Add aggregation SQL expression'
+ }
+ emptyLabel="Add aggregation SQL expression"
+ onChange={(customExpression) => setValueCustomExpression(index, customExpression)}
+ />
+ ) : null}
+ <RemoveFieldButton
+ field={value.field}
+ onClick={() => removeFieldFromShelf('values', index)}
+ />
+ </div>
+ ))}
+ </Shelf>
+
+ <Shelf
+ shelf="filters"
+ title="Filters"
+ description="Limit which rows are included"
+ icon={<IconFilter />}
+ itemCount={config.filters.length}
+ isActiveDropTarget={activeDropShelf === 'filters'}
+ onDropField={addFieldToShelf}
+ onActiveDropTargetChange={(active) =>
+ active ? setActiveDropShelf('filters') : clearActiveDropShelf('filters')
+ }
+ onAddField={() => addBlankFieldToShelf('filters')}
+ addFieldDisabledReason={!config.source ? 'Select a data source first' : undefined}
+ >
+ {config.filters.map((filter, index) => {
+ const filterNeedsValue = !['last_7_days', 'is_set', 'is_not_set', 'custom'].includes(
+ filter.operator
+ )
+ return (
+ <div key={filter.field.id} className="flex w-full min-w-0 items-center gap-2 rounded">
+ <ExpressionEditorButton
+ value={filter.field.expression}
+ field={filter.field}
+ label="Edit field expression"
+ emptyLabel="Select field"
+ visible={activeExpressionEditorId === filter.field.id ? true : undefined}
+ onVisibilityChange={(visible) => {
+ if (!visible) {
+ setActiveExpressionEditorId(null)
+ }
+ }}
+ onChange={(expression) => setFieldExpression('filters', index, expression)}
+ />
+ <DateBucketSelect
+ field={filter.field}
+ onChange={(dateBucket) => setFieldDateBucket('filters', index, dateBucket)}
+ />
+ <LemonSelect
+ value={filter.operator}
+ options={FILTER_OPERATOR_OPTIONS.map((option) => ({
+ ...option,
+ disabledReason:
+ option.value === 'last_7_days' && !isDateTimeBIField(filter.field)
+ ? 'Choose a date or date-time field'
+ : undefined,
+ }))}
+ onChange={(operator) => setFilterOperator(index, operator)}
+ size="xsmall"
+ dropdownMatchSelectWidth={false}
+ />
+ {filter.operator === 'custom' ? (
+ <ExpressionEditorButton
+ value={filter.customExpression ?? ''}
+ field={filter.field}
+ label={
+ filter.customExpression
+ ? 'Edit filter SQL condition'
+ : 'Add filter SQL condition'
+ }
+ emptyLabel="Add filter SQL condition"
+ onChange={(customExpression) =>
+ setFilterCustomExpression(index, customExpression)
+ }
+ />
+ ) : filterNeedsValue ? (
+ isDateTimeBIField(filter.field) ? (
+ <DateTimeFilterInput
+ field={filter.field}
+ value={filter.value}
+ onChange={(value) => setFilterValue(index, value)}
+ />
+ ) : (
+ <LemonInput
+ value={filter.value}
+ onChange={(value) => setFilterValue(index, value)}
+ placeholder="Value"
+ aria-label={`${filter.field.name} filter value`}
+ size="small"
+ />
+ )
+ ) : null}
+ <RemoveFieldButton
+ field={filter.field}
+ onClick={() => removeFieldFromShelf('filters', index)}
+ />
+ </div>
+ )
+ })}
+ </Shelf>
+ </div>
+ <Resizer {...biEditorResizerProps} />
+ </div>
+ )
+}
+
+function FieldExpressionEditor({
+ field,
+ autoOpen,
+ onAutoOpenClose,
+ onChange,
+ onDateBucketChange,
+ onRemove,
+}: {
+ field: BIField
+ autoOpen: boolean
+ onAutoOpenClose: () => void
+ onChange: (expression: string) => void
+ onDateBucketChange: (dateBucket: BIDateBucket | null) => void
+ onRemove: () => void
+}): JSX.Element {
+ return (
+ <div className="flex w-full min-w-0 items-center gap-2 rounded">
+ <ExpressionEditorButton
+ value={field.expression}
+ field={field}
+ label="Edit field expression"
+ emptyLabel="Select field"
+ visible={autoOpen ? true : undefined}
+ onVisibilityChange={(visible) => {
+ if (!visible) {
+ onAutoOpenClose()
+ }
+ }}
+ onChange={onChange}
+ />
+ <DateBucketSelect field={field} onChange={onDateBucketChange} />
+ <RemoveFieldButton field={field} onClick={onRemove} />
+ </div>
+ )
+}
+
+function DateBucketSelect({
+ field,
+ onChange,
+}: {
+ field: BIField
+ onChange: (dateBucket: BIDateBucket | null) => void
+}): JSX.Element | null {
+ if (!isDateTimeBIField(field)) {
+ return null
+ }
+
+ return (
+ <LemonSelect
+ value={field.dateBucket ?? null}
+ options={DATE_BUCKET_OPTIONS}
+ onChange={onChange}
+ size="xsmall"
+ dropdownMatchSelectWidth={false}
+ data-attr="bi-editor-date-bucket"
+ />
+ )
+}
+
+function RemoveFieldButton({ field, onClick }: { field: BIField; onClick: () => void }): JSX.Element {
+ const fieldName = field.name || 'field'
+
+ return (
+ <LemonButton
+ icon={<IconX />}
+ size="xsmall"
+ type="tertiary"
+ noPadding
+ className="shrink-0"
+ tooltip={`Remove ${fieldName}`}
+ aria-label={`Remove ${fieldName}`}
+ onClick={onClick}
+ />
+ )
+}
+
+function ExpressionEditorButton({
+ value,
+ field,
+ label,
+ emptyLabel,
+ visible,
+ onVisibilityChange,
+ onChange,
+}: {
+ value: string
+ field: BIField
+ label: string
+ emptyLabel?: string
+ visible?: boolean
+ onVisibilityChange?: (visible: boolean) => void
+ onChange: (value: string) => void
+}): JSX.Element {
+ return (
+ <HogQLDropdown
+ hogQLValue={value}
+ onHogQLValueChange={onChange}
+ tableName={field.source.table}
+ connectionId={field.source.connectionId}
+ size="small"
+ buttonIcon={<IconPencil />}
+ buttonLabel={value ? <code className="truncate">{value}</code> : emptyLabel}
+ buttonTooltip={label}
+ buttonAriaLabel={`${label} for ${field.name || 'field'}`}
+ visible={visible}
+ onVisibilityChange={onVisibilityChange}
+ />
+ )
+}
+
+function DateTimeFilterInput({
+ field,
+ value,
+ onChange,
+}: {
+ field: BIField
+ value: string
+ onChange: (value: string) => void
+}): JSX.Element {
+ const selectedDate = value && dayjs(value).isValid() ? dayjs(value) : null
+ const includesTime = field.type === 'datetime'
+
+ return (
+ <LemonCalendarSelectInput
+ value={selectedDate}
+ onChange={(date) => onChange(date?.format(includesTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD') ?? '')}
+ granularity={includesTime ? 'minute' : 'day'}
+ format={includesTime ? 'MMM D, YYYY HH:mm' : 'MMM D, YYYY'}
+ use24HourFormat
+ clearable
+ placeholder={includesTime ? 'Select date and time' : 'Select date'}
+ buttonProps={{ size: 'small', 'aria-label': `${field.name} filter date` }}
+ />
+ )
+}
+
+function Shelf({
+ shelf,
+ title,
+ description,
+ icon,
+ itemCount,
+ isActiveDropTarget,
+ children,
+ onDropField,
+ onActiveDropTargetChange,
+ onAddField,
+ addFieldDisabledReason,
+}: {
+ shelf: BIShelf
+ title: string
+ description: string
+ icon: ReactNode
+ itemCount: number
+ isActiveDropTarget: boolean
+ children: ReactNode
+ onDropField: (field: NonNullable<ReturnType<typeof parseBIField>>, shelf: BIShelf) => void
+ onActiveDropTargetChange: (active: boolean) => void
+ onAddField: () => void
+ addFieldDisabledReason?: string
+}): JSX.Element {
+ const handleDrop = (event: DragEvent<HTMLDivElement>): void => {
+ event.preventDefault()
+ onActiveDropTargetChange(false)
+ const field = parseBIField(event.dataTransfer.getData(BI_FIELD_DRAG_MIME_TYPE))
+ if (field) {
+ onDropField(field, shelf)
+ }
+ }
+
+ return (
+ <LemonCard
+ hoverEffect={false}
+ className={cn(
+ 'flex min-h-28 max-h-64 flex-col gap-2 overflow-hidden border-dashed p-3 transition-colors',
+ isActiveDropTarget && 'border-accent bg-accent-highlight-secondary ring-2 ring-inset ring-accent'
+ )}
+ >
+ <div
+ className="flex min-h-0 flex-1 flex-col gap-2"
+ data-attr={`bi-editor-${shelf}-shelf`}
+ onDragEnter={(event) => {
+ if (Array.from(event.dataTransfer.types).includes(BI_FIELD_DRAG_MIME_TYPE)) {
+ onActiveDropTargetChange(true)
+ }
+ }}
+ onDragOver={(event) => {
+ if (Array.from(event.dataTransfer.types).includes(BI_FIELD_DRAG_MIME_TYPE)) {
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'copy'
+ }
+ }}
+ onDragLeave={(event) => {
+ const nextTarget = event.relatedTarget
+ if (!nextTarget || !event.currentTarget.contains(nextTarget as Node)) {
+ onActiveDropTargetChange(false)
+ }
+ }}
+ onDrop={handleDrop}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2 font-medium">
+ <span className="text-tertiary">{icon}</span>
+ {title} ({itemCount})
+ </div>
+ <LemonButton
+ icon={<IconPlus />}
+ size="xsmall"
+ type="tertiary"
+ noPadding
+ tooltip="Add field"
+ aria-label={`Add field to ${title.toLowerCase()}`}
+ disabledReason={addFieldDisabledReason}
+ onClick={onAddField}
+ data-attr={`bi-editor-${shelf}-add-field`}
+ />
+ </div>
+ <span className="shrink-0 text-xs text-secondary">{description}</span>
+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto pr-1">{children}</div>
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
new file mode 100644
index 000000000000..c18a1612e841
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
@@ -0,0 +1,587 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import { uuid } from 'lib/utils/dom'
+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+
+import { DatabaseSchemaTable } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { sqlEditorLogic } from '../sqlEditorLogic'
+import type { QueryTab } from '../sqlEditorLogic'
+import {
+ BIAggregation,
+ BIConfig,
+ BIDataSource,
+ BIDateBucket,
+ BIEditorState,
+ BIEditorView,
+ BIField,
+ BIFilterOperator,
+ BIQueryBuildResult,
+ BIShelf,
+ DEFAULT_BI_CONFIG,
+ buildBIQuery,
+ createDefaultDateFilter,
+ defaultAggregationForField,
+ isBIFieldCompatible,
+} from './biEditorTypes'
+
+export interface BIEditorLogicProps {
+ tabId: string
+}
+
+function freshBIConfig(): BIConfig {
+ return {
+ ...DEFAULT_BI_CONFIG,
+ rows: [],
+ columns: [],
+ values: [],
+ filters: [],
+ }
+}
+
+function setDataSourceInConfig(config: BIConfig, source: BIDataSource): BIConfig {
+ if (
+ config.source?.table === source.table &&
+ (config.source.connectionId ?? null) === (source.connectionId ?? null)
+ ) {
+ return config
+ }
+
+ const defaultDateFilter = createDefaultDateFilter(source)
+
+ return {
+ ...config,
+ source,
+ rows: [],
+ columns: [],
+ values: [],
+ filters: defaultDateFilter ? [defaultDateFilter] : [],
+ }
+}
+
+function blankField(source: BIDataSource, fieldId: string): BIField {
+ return {
+ id: fieldId,
+ name: '',
+ expression: '',
+ type: 'unknown',
+ source,
+ }
+}
+
+function addFieldToConfig(config: BIConfig, field: BIField, shelf: BIShelf): BIConfig {
+ if (!isBIFieldCompatible(config.source, field)) {
+ return config
+ }
+
+ const source = config.source ?? field.source
+ const sourceConfig = config.source ? config : setDataSourceInConfig(config, source)
+
+ switch (shelf) {
+ case 'rows':
+ case 'columns':
+ if (sourceConfig[shelf].some((existingField) => existingField.id === field.id)) {
+ return sourceConfig
+ }
+ return { ...sourceConfig, source, [shelf]: [...sourceConfig[shelf], field] }
+ case 'values':
+ return {
+ ...sourceConfig,
+ source,
+ values: [...sourceConfig.values, { field, aggregation: defaultAggregationForField(field) }],
+ }
+ case 'filters':
+ if (
+ sourceConfig.filters.some(
+ (filter) =>
+ filter.field.id === field.id ||
+ (filter.field.expression === field.expression &&
+ filter.field.source.table === field.source.table &&
+ (filter.field.source.connectionId ?? null) === (field.source.connectionId ?? null))
+ )
+ ) {
+ return sourceConfig
+ }
+ return {
+ ...sourceConfig,
+ source,
+ filters: [...sourceConfig.filters, { field, operator: 'equals', value: '' }],
+ }
+ }
+}
+
+function removeFieldFromConfig(config: BIConfig, shelf: BIShelf, index: number): BIConfig {
+ switch (shelf) {
+ case 'rows':
+ case 'columns':
+ return { ...config, [shelf]: config[shelf].filter((_, fieldIndex) => fieldIndex !== index) }
+ case 'values':
+ return { ...config, values: config.values.filter((_, valueIndex) => valueIndex !== index) }
+ case 'filters':
+ return { ...config, filters: config.filters.filter((_, filterIndex) => filterIndex !== index) }
+ }
+}
+
+function setFieldExpressionInConfig(config: BIConfig, shelf: BIShelf, index: number, expression: string): BIConfig {
+ switch (shelf) {
+ case 'rows':
+ case 'columns':
+ return {
+ ...config,
+ [shelf]: config[shelf].map((field, fieldIndex) =>
+ fieldIndex === index ? { ...field, expression } : field
+ ),
+ }
+ case 'values':
+ return {
+ ...config,
+ values: config.values.map((value, valueIndex) =>
+ valueIndex === index ? { ...value, field: { ...value.field, expression } } : value
+ ),
+ }
+ case 'filters':
+ return {
+ ...config,
+ filters: config.filters.map((filter, filterIndex) =>
+ filterIndex === index ? { ...filter, field: { ...filter.field, expression } } : filter
+ ),
+ }
+ }
+}
+
+function setFieldDateBucketInConfig(
+ config: BIConfig,
+ shelf: BIShelf,
+ index: number,
+ dateBucket: BIDateBucket | null
+): BIConfig {
+ const updateField = (field: BIField): BIField => ({ ...field, dateBucket: dateBucket ?? undefined })
+
+ switch (shelf) {
+ case 'rows':
+ case 'columns':
+ return {
+ ...config,
+ [shelf]: config[shelf].map((field, fieldIndex) => (fieldIndex === index ? updateField(field) : field)),
+ }
+ case 'values':
+ return {
+ ...config,
+ values: config.values.map((value, valueIndex) =>
+ valueIndex === index ? { ...value, field: updateField(value.field) } : value
+ ),
+ }
+ case 'filters':
+ return {
+ ...config,
+ filters: config.filters.map((filter, filterIndex) =>
+ filterIndex === index ? { ...filter, field: updateField(filter.field) } : filter
+ ),
+ }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biEditorLogicValues {
+ allTables: DatabaseSchemaTable[] // databaseTableListLogic
+ databaseConnectionId: string | null // databaseTableListLogic
+ databaseLoading: boolean // databaseTableListLogic
+ posthogTables: DatabaseSchemaTable[] // databaseTableListLogic
+ activeTab: QueryTab | null // sqlEditorLogic
+ activeDropShelf: BIShelf | null
+ activeExpressionEditorId: string | null
+ availableDataSources: BIDataSource[]
+ config: BIConfig
+ editorView: BIEditorView
+ generatedQuery: BIQueryBuildResult | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biEditorLogicActions {
+ setSourceQuery: (sourceQuery: import('~/queries/schema/schema-general').DataVisualizationNode) => {
+ sourceQuery: import('~/queries/schema/schema-general').DataVisualizationNode
+ } // sqlEditorLogic
+ syncUrlWithQuery: () => {
+ value: true
+ } // sqlEditorLogic
+ updateTab: (tab: QueryTab) => {
+ tab: QueryTab
+ } // sqlEditorLogic
+ addBlankFieldToShelf: (shelf: BIShelf) => {
+ fieldId: string
+ shelf: BIShelf
+ }
+ addFieldToShelf: (
+ field: BIField,
+ shelf: BIShelf
+ ) => {
+ field: BIField
+ shelf: BIShelf
+ }
+ clearActiveDropShelf: (shelf: BIShelf) => {
+ shelf: BIShelf
+ }
+ persistState: (
+ editorView: BIEditorView,
+ config: BIConfig
+ ) => {
+ config: BIConfig
+ editorView: BIEditorView
+ }
+ removeFieldFromShelf: (
+ shelf: BIShelf,
+ index: number
+ ) => {
+ index: number
+ shelf: BIShelf
+ }
+ resetConfig: () => {
+ value: true
+ }
+ restoreState: (state: BIEditorState) => {
+ state: BIEditorState
+ }
+ setActiveDropShelf: (shelf: BIShelf) => {
+ shelf: BIShelf
+ }
+ setActiveExpressionEditorId: (fieldId: string | null) => {
+ fieldId: string | null
+ }
+ setChartType: (chartType: ChartDisplayType) => {
+ chartType: ChartDisplayType
+ }
+ setDataSource: (source: BIDataSource) => {
+ source: BIDataSource
+ }
+ setEditorView: (editorView: BIEditorView) => {
+ editorView: BIEditorView
+ }
+ setFieldDateBucket: (
+ shelf: BIShelf,
+ index: number,
+ dateBucket: BIDateBucket | null
+ ) => {
+ dateBucket: BIDateBucket | null
+ index: number
+ shelf: BIShelf
+ }
+ setFieldExpression: (
+ shelf: BIShelf,
+ index: number,
+ expression: string
+ ) => {
+ expression: string
+ index: number
+ shelf: BIShelf
+ }
+ setFilterCustomExpression: (
+ index: number,
+ customExpression: string
+ ) => {
+ customExpression: string
+ index: number
+ }
+ setFilterOperator: (
+ index: number,
+ operator: BIFilterOperator
+ ) => {
+ index: number
+ operator: BIFilterOperator
+ }
+ setFilterValue: (
+ index: number,
+ value: string
+ ) => {
+ index: number
+ value: string
+ }
+ setValueAggregation: (
+ index: number,
+ aggregation: BIAggregation
+ ) => {
+ aggregation: BIAggregation
+ index: number
+ }
+ setValueCustomExpression: (
+ index: number,
+ customExpression: string
+ ) => {
+ customExpression: string
+ index: number
+ }
+ syncGeneratedQuery: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biEditorLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ availableDataSources: (
+ allTables: DatabaseSchemaTable[],
+ posthogTables: DatabaseSchemaTable[],
+ databaseConnectionId: string | null
+ ) => BIDataSource[]
+ generatedQuery: (config: BIConfig) => BIQueryBuildResult | null
+ }
+}
+
+export type biEditorLogicType = MakeLogicType<
+ biEditorLogicValues,
+ biEditorLogicActions,
+ BIEditorLogicProps,
+ biEditorLogicMeta
+>
+
+export const biEditorLogic = kea<biEditorLogicType>([
+ props({} as BIEditorLogicProps),
+ key((logicProps) => logicProps.tabId),
+ path((logicKey) => ['data-warehouse', 'editor', 'biEditorLogic', logicKey]),
+ connect((logicProps: BIEditorLogicProps) => ({
+ values: [
+ sqlEditorLogic({ tabId: logicProps.tabId }),
+ ['activeTab'],
+ databaseTableListLogic,
+ ['allTables', 'posthogTables', 'connectionId as databaseConnectionId', 'databaseLoading'],
+ ],
+ actions: [sqlEditorLogic({ tabId: logicProps.tabId }), ['setSourceQuery', 'syncUrlWithQuery', 'updateTab']],
+ })),
+ actions({
+ setEditorView: (editorView: BIEditorView) => ({ editorView }),
+ restoreState: (state: BIEditorState) => ({ state }),
+ persistState: (editorView: BIEditorView, config: BIConfig) => ({ editorView, config }),
+ addFieldToShelf: (field: BIField, shelf: BIShelf) => ({ field, shelf }),
+ addBlankFieldToShelf: (shelf: BIShelf) => ({ shelf, fieldId: `bi-blank-${uuid()}` }),
+ clearActiveDropShelf: (shelf: BIShelf) => ({ shelf }),
+ removeFieldFromShelf: (shelf: BIShelf, index: number) => ({ shelf, index }),
+ setActiveDropShelf: (shelf: BIShelf) => ({ shelf }),
+ setActiveExpressionEditorId: (fieldId: string | null) => ({ fieldId }),
+ setChartType: (chartType: ChartDisplayType) => ({ chartType }),
+ setDataSource: (source: BIDataSource) => ({ source }),
+ setValueAggregation: (index: number, aggregation: BIAggregation) => ({ index, aggregation }),
+ setFilterOperator: (index: number, operator: BIFilterOperator) => ({ index, operator }),
+ setFilterValue: (index: number, value: string) => ({ index, value }),
+ setFieldExpression: (shelf: BIShelf, index: number, expression: string) => ({ shelf, index, expression }),
+ setFieldDateBucket: (shelf: BIShelf, index: number, dateBucket: BIDateBucket | null) => ({
+ shelf,
+ index,
+ dateBucket,
+ }),
+ setValueCustomExpression: (index: number, customExpression: string) => ({ index, customExpression }),
+ setFilterCustomExpression: (index: number, customExpression: string) => ({ index, customExpression }),
+ resetConfig: true,
+ syncGeneratedQuery: true,
+ }),
+ reducers({
+ activeDropShelf: [
+ null as BIShelf | null,
+ {
+ setActiveDropShelf: (_, { shelf }) => shelf,
+ clearActiveDropShelf: (activeDropShelf, { shelf }) =>
+ activeDropShelf === shelf ? null : activeDropShelf,
+ },
+ ],
+ activeExpressionEditorId: [
+ null as string | null,
+ {
+ addBlankFieldToShelf: (_, { fieldId }) => fieldId,
+ setActiveExpressionEditorId: (_, { fieldId }) => fieldId,
+ resetConfig: () => null,
+ restoreState: () => null,
+ setDataSource: () => null,
+ setEditorView: () => null,
+ },
+ ],
+ editorView: [
+ BIEditorView.SQL as BIEditorView,
+ {
+ setEditorView: (_, { editorView }) => editorView,
+ restoreState: (_, { state }) => state.editorView,
+ persistState: (_, { editorView }) => editorView,
+ updateTab: (_, { tab }) => tab.biEditorState?.editorView ?? BIEditorView.SQL,
+ },
+ ],
+ config: [
+ freshBIConfig(),
+ {
+ addFieldToShelf: (config, { field, shelf }) => addFieldToConfig(config, field, shelf),
+ addBlankFieldToShelf: (config, { shelf, fieldId }) =>
+ config.source ? addFieldToConfig(config, blankField(config.source, fieldId), shelf) : config,
+ removeFieldFromShelf: (config, { shelf, index }) => removeFieldFromConfig(config, shelf, index),
+ setChartType: (config, { chartType }) => ({ ...config, chartType }),
+ setDataSource: (config, { source }) => setDataSourceInConfig(config, source),
+ setValueAggregation: (config, { index, aggregation }) => ({
+ ...config,
+ values: config.values.map((value, valueIndex) =>
+ valueIndex === index ? { ...value, aggregation } : value
+ ),
+ }),
+ setFilterOperator: (config, { index, operator }) => ({
+ ...config,
+ filters: config.filters.map((filter, filterIndex) =>
+ filterIndex === index ? { ...filter, operator } : filter
+ ),
+ }),
+ setFilterValue: (config, { index, value }) => ({
+ ...config,
+ filters: config.filters.map((filter, filterIndex) =>
+ filterIndex === index ? { ...filter, value } : filter
+ ),
+ }),
+ setFieldExpression: (config, { shelf, index, expression }) =>
+ setFieldExpressionInConfig(config, shelf, index, expression),
+ setFieldDateBucket: (config, { shelf, index, dateBucket }) =>
+ setFieldDateBucketInConfig(config, shelf, index, dateBucket),
+ setValueCustomExpression: (config, { index, customExpression }) => ({
+ ...config,
+ values: config.values.map((value, valueIndex) =>
+ valueIndex === index ? { ...value, customExpression } : value
+ ),
+ }),
+ setFilterCustomExpression: (config, { index, customExpression }) => ({
+ ...config,
+ filters: config.filters.map((filter, filterIndex) =>
+ filterIndex === index ? { ...filter, customExpression } : filter
+ ),
+ }),
+ restoreState: (_, { state }) => state.config,
+ persistState: (_, { config }) => config,
+ updateTab: (_, { tab }) => tab.biEditorState?.config ?? freshBIConfig(),
+ resetConfig: freshBIConfig,
+ },
+ ],
+ }),
+ selectors({
+ availableDataSources: [
+ (selectors) => [selectors.allTables, selectors.posthogTables, selectors.databaseConnectionId],
+ (
+ allTables: DatabaseSchemaTable[],
+ posthogTables: DatabaseSchemaTable[],
+ databaseConnectionId: string | null
+ ): BIDataSource[] => {
+ const visiblePosthogTableNames = new Set(posthogTables.map((table) => table.name))
+ const availableTables = databaseConnectionId
+ ? allTables
+ : allTables.filter((table) => table.type !== 'posthog' || visiblePosthogTableNames.has(table.name))
+
+ return availableTables
+ .map((table) => ({ table: table.name, connectionId: databaseConnectionId ?? undefined }))
+ .sort((first, second) => first.table.localeCompare(second.table))
+ },
+ ],
+ generatedQuery: [
+ (selectors) => [selectors.config],
+ (config: BIConfig): BIQueryBuildResult | null => buildBIQuery(config),
+ ],
+ }),
+ listeners(({ actions, props: logicProps, values }) => ({
+ persistState: ({ editorView, config }) => {
+ if (!values.activeTab) {
+ return
+ }
+ actions.updateTab({
+ ...values.activeTab,
+ biEditorState: { editorView, config },
+ })
+ actions.syncUrlWithQuery()
+ },
+ setEditorView: ({ editorView }) => {
+ actions.persistState(editorView, values.config)
+ if (editorView === BIEditorView.BI) {
+ actions.syncGeneratedQuery()
+ }
+ },
+ addFieldToShelf: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ addBlankFieldToShelf: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ removeFieldFromShelf: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setChartType: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setDataSource: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setValueAggregation: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setFilterOperator: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setFilterValue: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setFieldExpression: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setFieldDateBucket: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setValueCustomExpression: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setFilterCustomExpression: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
+ setSourceQuery: ({ sourceQuery }) => {
+ if (!values.activeTab?.biEditorState && values.editorView === BIEditorView.SQL) {
+ return
+ }
+ actions.persistState(values.editorView, {
+ ...values.config,
+ chartType: sourceQuery.display ?? values.config.chartType,
+ })
+ },
+ resetConfig: () => {
+ actions.persistState(values.editorView, values.config)
+ const editorLogic = sqlEditorLogic({ tabId: logicProps.tabId })
+ const sourceQuery = editorLogic.values.sourceQuery
+ editorLogic.actions.setQueryInput('')
+ editorLogic.actions.setSourceQuery({
+ ...sourceQuery,
+ display: DEFAULT_BI_CONFIG.chartType,
+ source: { ...sourceQuery.source, query: '' },
+ })
+ },
+ syncGeneratedQuery: () => {
+ if (!values.generatedQuery) {
+ return
+ }
+
+ const editorLogic = sqlEditorLogic({ tabId: logicProps.tabId })
+ const sourceQuery = editorLogic.values.sourceQuery
+ editorLogic.actions.setQueryInput(values.generatedQuery.query)
+ editorLogic.actions.setSourceQuery({
+ ...sourceQuery,
+ ...values.generatedQuery.node,
+ source: {
+ ...sourceQuery.source,
+ ...values.generatedQuery.node.source,
+ },
+ })
+ },
+ })),
+ afterMount(({ actions, values }) => {
+ if (values.activeTab?.biEditorState) {
+ actions.restoreState(values.activeTab.biEditorState)
+ }
+ }),
+])
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
new file mode 100644
index 000000000000..f6a4822331c7
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
@@ -0,0 +1,279 @@
+import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import {
+ BIConfig,
+ BIField,
+ buildBIQuery,
+ createDefaultDateFilter,
+ defaultAggregationForField,
+ getBIDataSourceKey,
+ getBIFieldId,
+ isBIFieldCompatible,
+} from './biEditorTypes'
+
+const eventField: BIField = {
+ id: 'warehouse:events:event',
+ name: 'event',
+ expression: 'event',
+ type: 'string',
+ source: { table: 'events' },
+}
+
+const revenueField: BIField = {
+ id: 'warehouse:events:properties.revenue',
+ name: 'revenue',
+ expression: 'properties.revenue',
+ type: 'float',
+ source: { table: 'events' },
+}
+
+const timestampField: BIField = {
+ id: 'warehouse:events:timestamp',
+ name: 'timestamp',
+ expression: 'timestamp',
+ type: 'datetime',
+ source: { table: 'events' },
+}
+
+describe('BI editor query generation', () => {
+ it('builds a visualization node with dimensions, aggregations, and filters', () => {
+ const expectedQuery = [
+ 'SELECT',
+ ' event,',
+ ' sum(properties.revenue) AS sum_revenue',
+ 'FROM events',
+ 'WHERE',
+ " lower(event) LIKE lower('%sign\\'up%')",
+ 'GROUP BY',
+ ' event',
+ 'LIMIT 1000',
+ ].join('\n')
+ const config: BIConfig = {
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsBar,
+ rows: [eventField],
+ columns: [],
+ values: [{ field: revenueField, aggregation: 'sum' }],
+ filters: [{ field: eventField, operator: 'contains', value: "sign'up" }],
+ limit: 1000,
+ }
+
+ expect(buildBIQuery(config)).toEqual({
+ query: expectedQuery,
+ node: {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: expectedQuery,
+ connectionId: undefined,
+ },
+ display: ChartDisplayType.ActionsBar,
+ },
+ })
+ })
+
+ it('uses a row count when no value field has been added', () => {
+ const result = buildBIQuery({
+ source: { table: 'events' },
+ chartType: ChartDisplayType.Auto,
+ rows: [eventField],
+ columns: [],
+ values: [],
+ filters: [],
+ limit: 100,
+ })
+
+ expect(result?.query).toContain('count(*) AS count')
+ })
+
+ it('ignores blank shelf fields until they are configured', () => {
+ const blankField: BIField = {
+ id: 'blank-field',
+ name: '',
+ expression: '',
+ type: 'unknown',
+ source: { table: 'events' },
+ }
+ const result = buildBIQuery({
+ source: { table: 'events' },
+ chartType: ChartDisplayType.Auto,
+ rows: [blankField],
+ columns: [blankField],
+ values: [{ field: blankField, aggregation: 'count_distinct' }],
+ filters: [{ field: blankField, operator: 'equals', value: 'signup' }],
+ limit: 100,
+ })
+
+ expect(result?.query).toEqual(['SELECT', ' count(*) AS count', 'FROM events', 'LIMIT 100'].join('\n'))
+ })
+
+ it('uses a row count when a custom aggregation expression is blank', () => {
+ const result = buildBIQuery({
+ source: { table: 'events' },
+ chartType: ChartDisplayType.Auto,
+ rows: [eventField],
+ columns: [],
+ values: [{ field: revenueField, aggregation: 'custom', customExpression: ' ' }],
+ filters: [],
+ limit: 100,
+ })
+
+ expect(result?.query).toEqual(
+ ['SELECT', ' event,', ' count(*) AS count', 'FROM events', 'GROUP BY', ' event', 'LIMIT 100'].join(
+ '\n'
+ )
+ )
+ })
+
+ it('keeps nested object paths and explicit SQL expressions in the generated query', () => {
+ const browserField: BIField = {
+ id: 'warehouse:events:properties',
+ name: 'properties',
+ expression: 'properties.$browser',
+ type: 'json',
+ source: { table: 'events' },
+ }
+ const result = buildBIQuery({
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsBar,
+ rows: [browserField],
+ columns: [],
+ values: [
+ {
+ field: revenueField,
+ aggregation: 'custom',
+ customExpression: "sumIf(properties.revenue, event = 'purchase')",
+ },
+ ],
+ filters: [
+ { field: timestampField, operator: 'greater_than', value: '2026-08-04 09:30:00' },
+ {
+ field: browserField,
+ operator: 'custom',
+ value: '',
+ customExpression: "properties.$browser != 'HeadlessChrome'",
+ },
+ ],
+ limit: 100,
+ })
+
+ expect(result?.query).toContain('properties.$browser')
+ expect(result?.query).toContain("sumIf(properties.revenue, event = 'purchase') AS custom_revenue")
+ expect(result?.query).toContain("timestamp > '2026-08-04 09:30:00'")
+ expect(result?.query).toContain("properties.$browser != 'HeadlessChrome'")
+ })
+
+ test.each([
+ ['events', 'timestamp'],
+ ['sessions', '$start_timestamp'],
+ ['heatmaps', 'timestamp'],
+ ['session_replay_events', 'start_time'],
+ ['raw_session_replay_events', 'min_first_timestamp'],
+ ])('creates a relative date filter for the %s table', (table, expression) => {
+ const filter = createDefaultDateFilter({ table })
+
+ expect(filter).toEqual({
+ field: expect.objectContaining({ expression, source: { table }, type: 'datetime' }),
+ operator: 'last_7_days',
+ value: '',
+ })
+ })
+
+ test.each([
+ ['a table without a default', { table: 'persons' }],
+ ['an external table', { table: 'events', connectionId: 'warehouse-1' }],
+ ])('does not create a relative date filter for %s', (_name, source) => {
+ expect(createDefaultDateFilter(source)).toBeNull()
+ })
+
+ it('generates a relative date condition for the last 7 days', () => {
+ const result = buildBIQuery({
+ source: { table: 'events' },
+ chartType: ChartDisplayType.Auto,
+ rows: [],
+ columns: [],
+ values: [],
+ filters: [{ field: timestampField, operator: 'last_7_days', value: '' }],
+ limit: 100,
+ })
+
+ expect(result?.query).toContain('timestamp >= now() - INTERVAL 7 DAY')
+ })
+
+ test.each([
+ ['minute', 'toStartOfMinute'],
+ ['hour', 'toStartOfHour'],
+ ['day', 'toStartOfDay'],
+ ['week', 'toStartOfWeek'],
+ ['month', 'toStartOfMonth'],
+ ['quarter', 'toStartOfQuarter'],
+ ['year', 'toStartOfYear'],
+ ] as const)('groups date-time fields by %s', (dateBucket, dateBucketFunction) => {
+ const result = buildBIQuery({
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsLineGraph,
+ rows: [{ ...timestampField, dateBucket }],
+ columns: [],
+ values: [],
+ filters: [],
+ limit: 100,
+ })
+
+ expect(result?.query).toContain(`${dateBucketFunction}(timestamp)`)
+ })
+
+ test.each([
+ ['id', 'integer', 'count'],
+ ['uuid', 'string', 'count'],
+ ['events_id', 'integer', 'count'],
+ ['revenue', 'float', 'sum'],
+ ['event', 'string', 'count_distinct'],
+ ] as const)('uses %s fields with type %s as a %s value', (name, type, aggregation) => {
+ expect(
+ defaultAggregationForField({
+ id: `warehouse:events:${name}`,
+ name,
+ expression: name,
+ type,
+ source: { table: 'events' },
+ })
+ ).toBe(aggregation)
+ })
+
+ test.each([
+ ['the selected table', { table: 'events' }, { ...eventField, expression: 'properties.browser' }, true],
+ ['a different table', { table: 'events' }, { ...eventField, source: { table: 'persons' } }, false],
+ [
+ 'the same table on another connection',
+ { table: 'events' },
+ { ...eventField, source: { table: 'events', connectionId: '1' } },
+ false,
+ ],
+ [
+ 'the selected direct connection',
+ { table: 'events', connectionId: '1' },
+ { ...eventField, source: { table: 'events', connectionId: '1' } },
+ true,
+ ],
+ [
+ 'another direct connection with the same table',
+ { table: 'events', connectionId: '1' },
+ { ...eventField, source: { table: 'events', connectionId: '2' } },
+ false,
+ ],
+ ])('accepts fields from %s according to the active source', (_name, source, field, expected) => {
+ expect(isBIFieldCompatible(source, field)).toBe(expected)
+ })
+
+ it('keeps same-named sources and fields distinct across connections', () => {
+ const sources = [
+ { table: 'events' },
+ { table: 'events', connectionId: 'direct-1' },
+ { table: 'events', connectionId: 'direct-2' },
+ ]
+
+ expect(new Set(sources.map(getBIDataSourceKey)).size).toBe(sources.length)
+ expect(new Set(sources.map((source) => getBIFieldId(source, 'event'))).size).toBe(sources.length)
+ })
+})
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
new file mode 100644
index 000000000000..d0f5e448a9d3
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
@@ -0,0 +1,486 @@
+import { DataVisualizationNode, DatabaseSerializedFieldType, NodeKind } from '~/queries/schema/schema-general'
+import { escapeDottedHogQLIdentifier, escapeHogQLString, escapePropertyAsHogQLIdentifier } from '~/queries/utils'
+import { ChartDisplayType } from '~/types'
+
+export enum BIEditorView {
+ SQL = 'sql',
+ BI = 'bi',
+}
+
+export type BIShelf = 'rows' | 'columns' | 'values' | 'filters'
+
+export type BIAggregation = 'count' | 'count_distinct' | 'sum' | 'average' | 'minimum' | 'maximum' | 'custom'
+
+export type BIDateBucket = 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'
+
+export type BIFilterOperator =
+ | 'equals'
+ | 'not_equals'
+ | 'contains'
+ | 'greater_than'
+ | 'less_than'
+ | 'last_7_days'
+ | 'is_set'
+ | 'is_not_set'
+ | 'custom'
+
+export interface BIDataSource {
+ table: string
+ connectionId?: string
+}
+
+export function getBIDataSourceKey(source: BIDataSource): string {
+ return JSON.stringify([source.connectionId ?? null, source.table])
+}
+
+export function getBIFieldId(source: BIDataSource, expression: string): string {
+ return JSON.stringify([source.connectionId ?? null, source.table, expression])
+}
+
+export interface BIField {
+ id: string
+ name: string
+ expression: string
+ type: DatabaseSerializedFieldType
+ source: BIDataSource
+ dateBucket?: BIDateBucket
+}
+
+export interface BIValue {
+ field: BIField
+ aggregation: BIAggregation
+ customExpression?: string
+}
+
+export interface BIFilter {
+ field: BIField
+ operator: BIFilterOperator
+ value: string
+ customExpression?: string
+}
+
+export interface BIConfig {
+ source: BIDataSource | null
+ chartType: ChartDisplayType
+ rows: BIField[]
+ columns: BIField[]
+ values: BIValue[]
+ filters: BIFilter[]
+ limit: number
+}
+
+export interface BIEditorState {
+ editorView: BIEditorView
+ config: BIConfig
+}
+
+export interface BIQueryBuildResult {
+ query: string
+ node: DataVisualizationNode
+}
+
+export const BI_FIELD_DRAG_MIME_TYPE = 'application/x-posthog-bi-field'
+
+export const DEFAULT_BI_CONFIG: BIConfig = {
+ source: null,
+ chartType: ChartDisplayType.Auto,
+ rows: [],
+ columns: [],
+ values: [],
+ filters: [],
+ limit: 1000,
+}
+
+const BI_AGGREGATIONS = new Set<BIAggregation>([
+ 'count',
+ 'count_distinct',
+ 'sum',
+ 'average',
+ 'minimum',
+ 'maximum',
+ 'custom',
+])
+const BI_FILTER_OPERATORS = new Set<BIFilterOperator>([
+ 'equals',
+ 'not_equals',
+ 'contains',
+ 'greater_than',
+ 'less_than',
+ 'last_7_days',
+ 'is_set',
+ 'is_not_set',
+ 'custom',
+])
+const BI_DATE_BUCKETS = new Set<BIDateBucket>(['minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'])
+
+const DATE_BUCKET_FUNCTIONS: Record<BIDateBucket, string> = {
+ minute: 'toStartOfMinute',
+ hour: 'toStartOfHour',
+ day: 'toStartOfDay',
+ week: 'toStartOfWeek',
+ month: 'toStartOfMonth',
+ quarter: 'toStartOfQuarter',
+ year: 'toStartOfYear',
+}
+
+const DEFAULT_DATE_FIELD_BY_TABLE: Record<string, string> = {
+ events: 'timestamp',
+ sessions: '$start_timestamp',
+ heatmaps: 'timestamp',
+ session_replay_events: 'start_time',
+ raw_session_replay_events: 'min_first_timestamp',
+}
+
+const NUMERIC_FIELD_TYPES = new Set<DatabaseSerializedFieldType>(['integer', 'float', 'decimal'])
+
+export function isNumericBIField(field: BIField): boolean {
+ return NUMERIC_FIELD_TYPES.has(field.type)
+}
+
+export function isDateTimeBIField(field: BIField): boolean {
+ return field.type === 'date' || field.type === 'datetime'
+}
+
+export function isBIFieldCompatible(source: BIDataSource | null, field: BIField): boolean {
+ return (
+ !source ||
+ (source.table === field.source.table && (source.connectionId ?? null) === (field.source.connectionId ?? null))
+ )
+}
+
+export function defaultAggregationForField(field: BIField): BIAggregation {
+ const baseTableName = field.source.table.replaceAll('`', '').split('.').pop() ?? field.source.table
+ if (['id', 'uuid', `${baseTableName}_id`].includes(field.name)) {
+ return 'count'
+ }
+
+ return isNumericBIField(field) ? 'sum' : 'count_distinct'
+}
+
+export function createDefaultDateFilter(source: BIDataSource): BIFilter | null {
+ if (source.connectionId) {
+ return null
+ }
+
+ const expression = DEFAULT_DATE_FIELD_BY_TABLE[source.table]
+ if (!expression) {
+ return null
+ }
+
+ return {
+ field: {
+ id: `bi-default:${source.table}:${expression}`,
+ name: expression,
+ expression,
+ type: 'datetime',
+ source,
+ },
+ operator: 'last_7_days',
+ value: '',
+ }
+}
+
+export function serializeBIField(field: BIField): string {
+ return JSON.stringify(field)
+}
+
+function parseBIFieldValue(value: unknown): BIField | null {
+ if (!value || typeof value !== 'object') {
+ return null
+ }
+
+ const candidate = value as Partial<BIField>
+ if (
+ typeof candidate.id !== 'string' ||
+ typeof candidate.name !== 'string' ||
+ typeof candidate.expression !== 'string' ||
+ typeof candidate.type !== 'string' ||
+ (candidate.dateBucket !== undefined &&
+ (!BI_DATE_BUCKETS.has(candidate.dateBucket) ||
+ (candidate.type !== 'date' && candidate.type !== 'datetime'))) ||
+ !candidate.source ||
+ typeof candidate.source.table !== 'string' ||
+ (candidate.source.connectionId !== undefined && typeof candidate.source.connectionId !== 'string')
+ ) {
+ return null
+ }
+
+ return candidate as BIField
+}
+
+export function parseBIField(serializedField: string): BIField | null {
+ try {
+ return parseBIFieldValue(JSON.parse(serializedField))
+ } catch {
+ return null
+ }
+}
+
+export function parseBIEditorState(editorViewValue: unknown, configValue: unknown): BIEditorState | null {
+ if (editorViewValue !== BIEditorView.SQL && editorViewValue !== BIEditorView.BI) {
+ return null
+ }
+
+ if (configValue === undefined) {
+ return {
+ editorView: editorViewValue,
+ config: { ...DEFAULT_BI_CONFIG, rows: [], columns: [], values: [], filters: [] },
+ }
+ }
+
+ let decodedConfig = configValue
+ if (typeof configValue === 'string') {
+ try {
+ decodedConfig = JSON.parse(configValue)
+ } catch {
+ return null
+ }
+ }
+ if (!decodedConfig || typeof decodedConfig !== 'object') {
+ return null
+ }
+
+ const candidate = decodedConfig as Partial<BIConfig>
+ const source =
+ candidate.source === null
+ ? null
+ : candidate.source &&
+ typeof candidate.source.table === 'string' &&
+ (candidate.source.connectionId === undefined || typeof candidate.source.connectionId === 'string')
+ ? candidate.source
+ : undefined
+ const rows = Array.isArray(candidate.rows) ? candidate.rows.map(parseBIFieldValue) : null
+ const columns = Array.isArray(candidate.columns) ? candidate.columns.map(parseBIFieldValue) : null
+ const values = Array.isArray(candidate.values)
+ ? candidate.values.map((value): BIValue | null => {
+ if (!value || typeof value !== 'object') {
+ return null
+ }
+ const valueCandidate = value as Partial<BIValue>
+ const field = parseBIFieldValue(valueCandidate.field)
+ if (
+ !field ||
+ !BI_AGGREGATIONS.has(valueCandidate.aggregation as BIAggregation) ||
+ (valueCandidate.customExpression !== undefined && typeof valueCandidate.customExpression !== 'string')
+ ) {
+ return null
+ }
+ return {
+ field,
+ aggregation: valueCandidate.aggregation as BIAggregation,
+ customExpression: valueCandidate.customExpression,
+ }
+ })
+ : null
+ const filters = Array.isArray(candidate.filters)
+ ? candidate.filters.map((filter): BIFilter | null => {
+ if (!filter || typeof filter !== 'object') {
+ return null
+ }
+ const filterCandidate = filter as Partial<BIFilter>
+ const field = parseBIFieldValue(filterCandidate.field)
+ if (
+ !field ||
+ !BI_FILTER_OPERATORS.has(filterCandidate.operator as BIFilterOperator) ||
+ typeof filterCandidate.value !== 'string' ||
+ (filterCandidate.customExpression !== undefined &&
+ typeof filterCandidate.customExpression !== 'string')
+ ) {
+ return null
+ }
+ return {
+ field,
+ operator: filterCandidate.operator as BIFilterOperator,
+ value: filterCandidate.value,
+ customExpression: filterCandidate.customExpression,
+ }
+ })
+ : null
+
+ if (
+ source === undefined ||
+ !Object.values(ChartDisplayType).includes(candidate.chartType as ChartDisplayType) ||
+ !rows ||
+ rows.some((field) => !field) ||
+ !columns ||
+ columns.some((field) => !field) ||
+ !values ||
+ values.some((value) => !value) ||
+ !filters ||
+ filters.some((filter) => !filter) ||
+ typeof candidate.limit !== 'number' ||
+ !Number.isInteger(candidate.limit) ||
+ candidate.limit <= 0
+ ) {
+ return null
+ }
+
+ const config: BIConfig = {
+ source,
+ chartType: candidate.chartType as ChartDisplayType,
+ rows: rows as BIField[],
+ columns: columns as BIField[],
+ values: values as BIValue[],
+ filters: filters as BIFilter[],
+ limit: candidate.limit,
+ }
+ const fields = [
+ ...config.rows,
+ ...config.columns,
+ ...config.values.map((value) => value.field),
+ ...config.filters.map((filter) => filter.field),
+ ]
+
+ if (fields.length > 0 && (!source || fields.some((field) => !isBIFieldCompatible(source, field)))) {
+ return null
+ }
+
+ return { editorView: editorViewValue, config }
+}
+
+function sanitizeAlias(value: string): string {
+ const alias = value
+ .replaceAll(/[^a-zA-Z0-9_]+/g, '_')
+ .replaceAll(/^_+|_+$/g, '')
+ .toLowerCase()
+
+ return alias || 'value'
+}
+
+const DOTTED_IDENTIFIER_REGEX = /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/
+
+function fieldExpression(field: BIField): string {
+ const expression = field.expression.trim() || field.name
+ const escapedExpression = DOTTED_IDENTIFIER_REGEX.test(expression)
+ ? escapeDottedHogQLIdentifier(expression)
+ : expression
+
+ return field.dateBucket ? `${DATE_BUCKET_FUNCTIONS[field.dateBucket]}(${escapedExpression})` : escapedExpression
+}
+
+function aggregationExpression(value: BIValue): string | null {
+ if (value.aggregation === 'custom') {
+ return value.customExpression?.trim() || null
+ }
+
+ const field = fieldExpression(value.field)
+
+ if (!field) {
+ return null
+ }
+
+ switch (value.aggregation) {
+ case 'count':
+ return `count(${field})`
+ case 'count_distinct':
+ return `count(DISTINCT ${field})`
+ case 'sum':
+ return `sum(${field})`
+ case 'average':
+ return `avg(${field})`
+ case 'minimum':
+ return `min(${field})`
+ case 'maximum':
+ return `max(${field})`
+ }
+}
+
+function filterExpression(filter: BIFilter): string | null {
+ const field = fieldExpression(filter.field)
+
+ if (filter.operator === 'custom') {
+ return filter.customExpression?.trim() || null
+ }
+
+ if (filter.operator === 'is_set') {
+ return `${field} IS NOT NULL`
+ }
+ if (filter.operator === 'is_not_set') {
+ return `${field} IS NULL`
+ }
+ if (filter.operator === 'last_7_days') {
+ return `${field} >= now() - INTERVAL 7 DAY`
+ }
+ if (!filter.value.trim()) {
+ return null
+ }
+
+ const value =
+ isNumericBIField(filter.field) && Number.isFinite(Number(filter.value))
+ ? String(Number(filter.value))
+ : escapeHogQLString(filter.value)
+
+ switch (filter.operator) {
+ case 'equals':
+ return `${field} = ${value}`
+ case 'not_equals':
+ return `${field} != ${value}`
+ case 'contains':
+ return `lower(${field}) LIKE lower(${escapeHogQLString(`%${filter.value}%`)})`
+ case 'greater_than':
+ return `${field} > ${value}`
+ case 'less_than':
+ return `${field} < ${value}`
+ }
+}
+
+export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
+ if (!config.source) {
+ return null
+ }
+
+ const dimensions = [...config.rows, ...config.columns].filter(
+ (field) => field.expression.trim() || field.name.trim()
+ )
+ const dimensionExpressions = dimensions.map(fieldExpression)
+ const configuredValues = config.values
+ .map((value) => ({ value, expression: aggregationExpression(value) }))
+ .filter(
+ (configuredValue): configuredValue is { value: BIValue; expression: string } => !!configuredValue.expression
+ )
+ const valueExpressions =
+ configuredValues.length > 0
+ ? configuredValues.map(({ value, expression }, index) => {
+ const alias = `${value.aggregation}_${sanitizeAlias(value.field.name)}${index > 0 ? `_${index + 1}` : ''}`
+ return `${expression} AS ${escapePropertyAsHogQLIdentifier(alias)}`
+ })
+ : ['count(*) AS count']
+ const selectExpressions = [...dimensionExpressions, ...valueExpressions]
+ const filters = config.filters
+ .filter(
+ (filter) =>
+ filter.field.expression.trim() ||
+ filter.field.name.trim() ||
+ (filter.operator === 'custom' && filter.customExpression?.trim())
+ )
+ .map(filterExpression)
+ .filter((filter): filter is string => !!filter)
+ const queryParts = [
+ `SELECT\n ${selectExpressions.join(',\n ')}`,
+ `FROM ${escapePropertyAsHogQLIdentifier(config.source.table)}`,
+ ]
+
+ if (filters.length > 0) {
+ queryParts.push(`WHERE\n ${filters.join('\n AND ')}`)
+ }
+ if (dimensionExpressions.length > 0) {
+ queryParts.push(`GROUP BY\n ${dimensionExpressions.join(',\n ')}`)
+ }
+
+ queryParts.push(`LIMIT ${config.limit}`)
+
+ const query = queryParts.join('\n')
+
+ return {
+ query,
+ node: {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query,
+ connectionId: config.source.connectionId,
+ },
+ display: config.chartType,
+ },
+ }
+}
diff --git a/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsx
index a9b3a65e713a..eb2e7371af91 100644
--- a/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/editorSizingLogic.tsx
@@ -10,6 +10,7 @@ export interface EditorSizingLogicProps {
sidebarRef: React.RefObject<HTMLDivElement>
databaseTreeRef: React.RefObject<HTMLDivElement>
queryPaneDefaultHeight?: number
+ biEditorResizerProps: ResizerLogicProps
sourceNavigatorResizerProps: ResizerLogicProps
sidebarResizerProps: ResizerLogicProps
queryPaneResizerProps: ResizerLogicProps
@@ -20,6 +21,8 @@ const MINIMUM_NAVIGATOR_WIDTH = 100
const NAVIGATOR_DEFAULT_WIDTH = 350
const MINIMUM_QUERY_PANE_HEIGHT = 100
const DEFAULT_QUERY_PANE_HEIGHT = 300
+const MINIMUM_BI_EDITOR_HEIGHT = 180
+const DEFAULT_BI_EDITOR_HEIGHT = 324
const MINIMUM_SIDEBAR_WIDTH = 150
export const SIDEBAR_DEFAULT_WIDTH = 300
const MAXIMUM_SIDEBAR_WIDTH = 550
@@ -31,11 +34,14 @@ const DATABASE_TREE_COLLAPSED_WIDTH = 48
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface editorSizingLogicValues {
+ biEditorDesiredSize: number | null // resizerLogic
databaseTreeDesiredSize: number | null // resizerLogic
databaseTreeIsResizing: boolean // resizerLogic
queryPaneDesiredSize: number | null // resizerLogic
sidebarDesiredSize: number | null // resizerLogic
sourceNavigatorDesiredSize: number | null // resizerLogic
+ biEditorHeight: number
+ biEditorResizerProps: ResizerLogicProps
databaseTreeResizerProps: ResizerLogicProps
databaseTreeWidth: number
databaseTreeWillCollapse: boolean
@@ -80,6 +86,8 @@ export interface editorSizingLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
editorSceneRef: (editorSceneRef: any) => any
+ biEditorHeight: (biEditorDesiredSize: number | null) => number
+ biEditorResizerProps: (biEditorResizerProps: ResizerLogicProps) => ResizerLogicProps
sourceNavigatorWidth: (sourceNavigatorDesiredSize: number | null) => number
queryPaneHeight: (queryPaneDesiredSize: number | null, arg: number | undefined) => number
queryTabsWidth: (queryPaneDesiredSize: number | null) => number
@@ -111,6 +119,8 @@ export const editorSizingLogic = kea<editorSizingLogicType>([
['desiredSize as sidebarDesiredSize'],
resizerLogic(props.queryPaneResizerProps),
['desiredSize as queryPaneDesiredSize'],
+ resizerLogic(props.biEditorResizerProps),
+ ['desiredSize as biEditorDesiredSize'],
resizerLogic(props.databaseTreeResizerProps),
['desiredSize as databaseTreeDesiredSize', 'isResizeInProgress as databaseTreeIsResizing'],
],
@@ -166,6 +176,14 @@ export const editorSizingLogic = kea<editorSizingLogicType>([
})),
selectors({
editorSceneRef: [(p) => [p.editorSceneRef], (editorSceneRef) => editorSceneRef],
+ biEditorHeight: [
+ (s) => [s.biEditorDesiredSize],
+ (desiredSize: number | null) => Math.max(desiredSize || DEFAULT_BI_EDITOR_HEIGHT, MINIMUM_BI_EDITOR_HEIGHT),
+ ],
+ biEditorResizerProps: [
+ (_, p) => [p.biEditorResizerProps],
+ (biEditorResizerProps: ResizerLogicProps) => biEditorResizerProps,
+ ],
sourceNavigatorWidth: [
(s) => [s.sourceNavigatorDesiredSize],
(desiredSize: number | null) => Math.max(desiredSize || NAVIGATOR_DEFAULT_WIDTH, MINIMUM_NAVIGATOR_WIDTH),
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.test.ts b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.test.ts
index da8eef6d44cb..b040f901eafb 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.test.ts
@@ -4,7 +4,7 @@ describe('QueryDatabase', () => {
describe('getColumnInsertText', () => {
test.each([
['a column inserts its name at the cursor', { type: 'column', columnName: 'id' }, 'id'],
- // A row is free to render as a column without carrying a name — the notebook's dataframe
+ // A row can render as a column without carrying a name, as the notebook's dataframe
// section did for a while. Escaping the missing name throws, and the throw escapes the
// row's <a> handler before it can preventDefault, so the browser follows the placeholder
// href and drops the user on the project home page.
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
index e44d80f3596d..644bac03795f 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
@@ -38,6 +38,16 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
import { newInternalTab } from 'lib/utils/newInternalTab'
+import { biEditorLogic } from 'scenes/data-warehouse/editor/bi/biEditorLogic'
+import {
+ BI_FIELD_DRAG_MIME_TYPE,
+ BIDataSource,
+ BIEditorView,
+ BIField,
+ getBIFieldId,
+ isBIFieldCompatible,
+ serializeBIField,
+} from 'scenes/data-warehouse/editor/bi/biEditorTypes'
import { POSTHOG_WAREHOUSE } from 'scenes/data-warehouse/editor/connectionSelectorLogic'
import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
@@ -107,6 +117,7 @@ const filterTreeSections = (sections: TreeDataItem[], searchTerm: string): TreeD
export const QueryDatabase = ({
virtualizationScrollContainerRef,
extraTreeSections,
+ tabId,
}: {
virtualizationScrollContainerRef?: React.RefObject<HTMLDivElement | null>
/**
@@ -116,6 +127,7 @@ export const QueryDatabase = ({
* unaffected.
*/
extraTreeSections?: TreeDataItem[]
+ tabId: string
}): JSX.Element => {
const {
searchTerm,
@@ -129,6 +141,8 @@ export const QueryDatabase = ({
highlightViewsSectionDrop,
featureFlags,
} = useValues(queryDatabaseLogic)
+ const { config: biConfig, editorView } = useValues(biEditorLogic({ tabId }))
+ const isBIEditor = editorView === BIEditorView.BI
const {
setExpandedFolders,
toggleFolderOpen,
@@ -372,8 +386,10 @@ export const QueryDatabase = ({
<LemonTree
ref={treeRef}
data={treeData}
- enableDragAndDrop={!searchTerm}
- isItemDraggable={(item) => !searchTerm && item.record?.type === 'view' && item.record?.isSavedQuery}
+ enableDragAndDrop={!searchTerm && !isBIEditor}
+ isItemDraggable={(item) =>
+ !searchTerm && !isBIEditor && item.record?.type === 'view' && item.record?.isSavedQuery
+ }
isItemDroppable={(item) =>
!searchTerm &&
((item.record?.type === 'folder' && item.record?.folderType === 'view-folder') ||
@@ -417,7 +433,7 @@ export const QueryDatabase = ({
}
// Insert the column at the cursor, preserving the rest of the query the user has typed
- const columnInsertText = getColumnInsertText(item?.record)
+ const columnInsertText = isBIEditor ? null : getColumnInsertText(item?.record)
if (columnInsertText) {
insertTextAtCursor(columnInsertText)
}
@@ -431,6 +447,27 @@ export const QueryDatabase = ({
const matches = item.record?.searchMatches
const hasMatches = matches && matches.length > 0
const isColumn = item.record?.type === 'column'
+ const biFieldSource: BIDataSource | null =
+ isColumn && typeof item.record?.table === 'string'
+ ? {
+ table: item.record.table,
+ connectionId:
+ connectionId && connectionId !== POSTHOG_WAREHOUSE ? connectionId : undefined,
+ }
+ : null
+ const columnName =
+ isColumn && typeof item.record?.columnName === 'string' ? item.record.columnName : null
+ const biField: BIField | null =
+ biFieldSource && columnName
+ ? {
+ id: getBIFieldId(biFieldSource, columnName),
+ name: item.name,
+ expression: columnName,
+ type: item.record?.field.type,
+ source: biFieldSource,
+ }
+ : null
+ const canDragBIField = isBIEditor && !!biField && isBIFieldCompatible(biConfig.source, biField)
const columnType = isColumn ? item.record?.field?.type : null
const tableKindLabel = !isColumn && item.children?.length ? getTableKindLabel(item) : null
const certification =
@@ -452,7 +489,21 @@ export const QueryDatabase = ({
return (
<span
- className="truncate"
+ className={cn(
+ 'truncate',
+ isBIEditor && isColumn && 'cursor-grab',
+ isBIEditor && isColumn && !canDragBIField && 'cursor-not-allowed opacity-40'
+ )}
+ draggable={canDragBIField}
+ onDragStart={(event) => {
+ if (!biField || !canDragBIField) {
+ event.preventDefault()
+ return
+ }
+ event.stopPropagation()
+ event.dataTransfer.effectAllowed = 'copy'
+ event.dataTransfer.setData(BI_FIELD_DRAG_MIME_TYPE, serializeBIField(biField))
+ }}
onDoubleClick={(e) => {
if (!isPreviewableViewItem(item)) {
return
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
index 656e5e598a84..ea56429e0cc8 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
@@ -205,6 +205,46 @@ describe('queryDatabaseLogic', () => {
).toEqual(false)
})
+ it('opens and focuses a located table after the collapsed tree remounts', () => {
+ initKeaTests()
+ const logic = queryDatabaseLogic()
+ logic.mount()
+ databaseTableListLogic.findMounted()?.actions.loadDatabaseSuccess({
+ tables: {
+ events: {
+ id: 'events',
+ name: 'events',
+ type: 'posthog',
+ fields: {},
+ },
+ },
+ joins: [],
+ })
+ const focusItem = jest.fn()
+
+ logic.actions.locateTable('events')
+
+ expect(logic.values.expandedFolders).toEqual(
+ expect.arrayContaining(['sources', 'source-posthog', 'table-events'])
+ )
+ expect(logic.values.tableToLocate).toEqual('events')
+
+ logic.actions.setTreeRef({
+ current: {
+ focusItem,
+ getVisibleItems: () => [],
+ },
+ })
+
+ expect(focusItem).toHaveBeenCalledWith('table-events', {
+ scrollPosition: 'top-third',
+ behavior: 'smooth',
+ })
+ expect(logic.values.tableToLocate).toBeNull()
+
+ logic.unmount()
+ })
+
describe('failed schema load', () => {
let logic: ReturnType<typeof queryDatabaseLogic.build>
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index 79eaa6576732..edf21277182a 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -1340,6 +1340,41 @@ const findTreeItem = (items: TreeDataItem[], targetId: string): TreeDataItem | n
return path ? path[path.length - 1] : null
}
+const getTreeItemDataSourceName = (item: TreeDataItem): string | null => {
+ switch (item.record?.type) {
+ case 'table':
+ return item.record.table?.name ?? item.name
+ case 'view':
+ case 'managed-view':
+ return item.record.view?.name ?? item.name
+ case 'endpoint':
+ return item.record.tableName ?? item.record.table?.name ?? item.name
+ default:
+ return null
+ }
+}
+
+const findDataSourceTreePath = (
+ items: TreeDataItem[],
+ tableName: string,
+ path: TreeDataItem[] = []
+): TreeDataItem[] | null => {
+ for (const item of items) {
+ const nextPath = [...path, item]
+ if (getTreeItemDataSourceName(item) === tableName) {
+ return nextPath
+ }
+ if (item.children) {
+ const foundPath = findDataSourceTreePath(item.children, tableName, nextPath)
+ if (foundPath) {
+ return foundPath
+ }
+ }
+ }
+
+ return null
+}
+
const getFolderIdFromDropTarget = (items: TreeDataItem[], dropTargetId: string | null): string | null | undefined => {
if (dropTargetId === '') {
return null
@@ -1431,6 +1466,7 @@ export interface queryDatabaseLogicValues {
selectedSchema: DatabaseSchemaDataWarehouseTable | DatabaseSchemaTable | DataWarehouseSavedQuery | null
sidebarOverlayTreeItems: TreeItem[]
syncMoreNoticeDismissed: boolean
+ tableToLocate: string | null
treeData: TreeDataItem[]
treeDataContext: TreeDataContext
treeRef: EditorSidebarTreeRef
@@ -1543,6 +1579,9 @@ export interface queryDatabaseLogicActions {
clearSearch: () => {
value: true
}
+ clearTableToLocate: () => {
+ value: true
+ }
deleteUnsavedQuery: (record: Record<string, any>) => {
record: Record<string, any>
}
@@ -1595,6 +1634,9 @@ export interface queryDatabaseLogicActions {
queryTabState: QueryTabState | null
payload?: any
}
+ locateTable: (tableName: string) => {
+ tableName: string
+ }
moveDraggedViewToDropTarget: (
viewId: string,
dropTargetId: string | null
@@ -1818,6 +1860,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
setTreeRef: (ref: EditorSidebarTreeRef | null) => ({ ref }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
clearSearch: true,
+ clearTableToLocate: true,
+ locateTable: (tableName: string) => ({ tableName }),
selectSourceTable: (tableName: string) => ({ tableName }),
setSyncMoreNoticeDismissed: (dismissed: boolean) => ({ dismissed }),
setEditingDraft: (draftId: string) => ({ draftId }),
@@ -1935,6 +1979,13 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
setTreeRef: (_, { ref }) => ref,
},
],
+ tableToLocate: [
+ null as string | null,
+ {
+ locateTable: (_, { tableName }) => tableName,
+ clearTableToLocate: () => null,
+ },
+ ],
searchTerm: [
'',
@@ -2029,6 +2080,40 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
actions.clearPendingViewFolderOverrides()
},
})),
+ listeners(({ actions, values }) => {
+ const revealLocatedTable = (tableName: string): void => {
+ actions.clearSearch()
+ const path = findDataSourceTreePath(values.displayedTreeData, tableName)
+ if (!path) {
+ return
+ }
+
+ const tableId = path[path.length - 1].id
+ actions.setExpandedFolders(
+ Array.from(new Set([...values.expandedFolders, ...path.map((item) => item.id)])),
+ values.connectionId
+ )
+
+ if (values.treeRef?.current) {
+ values.treeRef.current.focusItem(tableId, {
+ scrollPosition: 'top-third',
+ behavior: 'smooth',
+ })
+ actions.clearTableToLocate()
+ }
+ }
+
+ return {
+ locateTable: ({ tableName }) => {
+ revealLocatedTable(tableName)
+ },
+ setTreeRef: ({ ref }) => {
+ if (ref?.current && values.tableToLocate) {
+ revealLocatedTable(values.tableToLocate)
+ }
+ },
+ }
+ }),
loaders(({ values }) => ({
queryTabState: [
null as QueryTabState | null,
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index d9ad24e21600..cf16a269e68c 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -26,6 +26,8 @@ import {
import { initKeaTests } from '~/test/init'
import { ChartDisplayType, InsightShortId, QueryBasedInsightModel } from '~/types'
+import { biEditorLogic } from './bi/biEditorLogic'
+import { BIConfig, BIEditorView, BIField } from './bi/biEditorTypes'
import { buildSqlNotebook, editorSceneLogic } from './editorSceneLogic'
import { OutputTab } from './outputPaneLogic'
import {
@@ -1478,6 +1480,219 @@ describe('sqlEditorLogic', () => {
})
})
+ describe('BI editor hash parameters', () => {
+ const eventField: BIField = {
+ id: 'warehouse:events:event',
+ name: 'event',
+ expression: 'event',
+ type: 'string',
+ source: { table: 'events' },
+ }
+ const timestampField: BIField = {
+ id: 'warehouse:events:timestamp',
+ name: 'timestamp',
+ expression: 'timestamp',
+ type: 'datetime',
+ source: { table: 'events' },
+ }
+ const config: BIConfig = {
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsBar,
+ rows: [eventField],
+ columns: [],
+ values: [],
+ filters: [{ field: eventField, operator: 'equals', value: 'signup' }],
+ limit: 1000,
+ }
+
+ it('offers every sidebar table while excluding hidden PostHog tables', () => {
+ const biLogic = biEditorLogic({ tabId: TAB_ID })
+ biLogic.mount()
+
+ databaseLogic.actions.loadDatabaseSuccess({
+ tables: {
+ persons: { id: 'persons', name: 'persons', type: 'posthog', fields: {} },
+ hidden_table: { id: 'hidden_table', name: 'hidden_table', type: 'posthog', fields: {} },
+ events: { id: 'events', name: 'events', type: 'posthog', fields: {} },
+ sessions: { id: 'sessions', name: 'sessions', type: 'posthog', fields: {} },
+ groups: { id: 'groups', name: 'groups', type: 'posthog', fields: {} },
+ custom_orders: { id: 'custom_orders', name: 'custom_orders', type: 'data_warehouse', fields: {} },
+ system_metrics: { id: 'system_metrics', name: 'system_metrics', type: 'system', fields: {} },
+ revenue_view: {
+ id: 'revenue_view',
+ name: 'revenue_view',
+ type: 'view',
+ fields: {},
+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },
+ },
+ },
+ joins: [],
+ })
+
+ expect(biLogic.values.availableDataSources).toEqual([
+ { table: 'custom_orders', connectionId: undefined },
+ { table: 'events', connectionId: undefined },
+ { table: 'groups', connectionId: undefined },
+ { table: 'persons', connectionId: undefined },
+ { table: 'revenue_view', connectionId: undefined },
+ { table: 'sessions', connectionId: undefined },
+ { table: 'system_metrics', connectionId: undefined },
+ ])
+
+ biLogic.unmount()
+ })
+
+ it('restores BI mode and configuration from the URL and keeps changes in the hash', async () => {
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ const biLogic = biEditorLogic({ tabId: TAB_ID })
+ biLogic.mount()
+
+ router.actions.push(urls.sqlEditor(), undefined, {
+ q: "SELECT event, count(*) FROM events WHERE event = 'signup' GROUP BY event",
+ mode: BIEditorView.BI,
+ bi: config,
+ })
+
+ await expectLogic(logic)
+ .toDispatchActions(['createTab', 'updateTab'])
+ .toMatchValues({
+ activeTab: partial({
+ biEditorState: { editorView: BIEditorView.BI, config },
+ }),
+ })
+ await expectLogic(biLogic).toMatchValues({ editorView: BIEditorView.BI, config })
+
+ await expectLogic(biLogic, () => biLogic.actions.setFilterValue(0, 'purchase')).toFinishAllListeners()
+
+ expect(router.values.hashParams.mode).toEqual(BIEditorView.BI)
+ expect(router.values.hashParams.bi).toEqual({
+ ...config,
+ filters: [{ ...config.filters[0], value: 'purchase' }],
+ })
+
+ biLogic.unmount()
+ })
+
+ it('regenerates the query and URL when a date bucket changes', async () => {
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ const biLogic = biEditorLogic({ tabId: TAB_ID })
+ biLogic.mount()
+ const dateConfig: BIConfig = { ...config, rows: [timestampField], filters: [] }
+
+ router.actions.push(urls.sqlEditor(), undefined, {
+ q: 'SELECT timestamp, count(*) FROM events GROUP BY timestamp',
+ mode: BIEditorView.BI,
+ bi: dateConfig,
+ })
+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
+
+ await expectLogic(biLogic, () => biLogic.actions.setFieldDateBucket('rows', 0, 'day'))
+ .toFinishAllListeners()
+ .toMatchValues({
+ config: partial({ rows: [{ ...timestampField, dateBucket: 'day' }] }),
+ })
+
+ expect(logic.values.queryInput).toContain('toStartOfDay(timestamp)')
+ expect(router.values.hashParams.bi).toEqual({
+ ...dateConfig,
+ rows: [{ ...timestampField, dateBucket: 'day' }],
+ })
+
+ biLogic.unmount()
+ })
+
+ it('clears incompatible fields and opens persisted blank shelf fields for editing', async () => {
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ const biLogic = biEditorLogic({ tabId: TAB_ID })
+ biLogic.mount()
+
+ router.actions.push(urls.sqlEditor(), undefined, {
+ q: 'SELECT event, count(*) FROM events GROUP BY event',
+ mode: BIEditorView.BI,
+ bi: config,
+ })
+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
+
+ await expectLogic(biLogic, () => biLogic.actions.setDataSource({ table: 'persons' }))
+ .toFinishAllListeners()
+ .toMatchValues({
+ config: partial({
+ source: { table: 'persons' },
+ rows: [],
+ columns: [],
+ values: [],
+ filters: [],
+ }),
+ })
+
+ await expectLogic(biLogic, () => biLogic.actions.addBlankFieldToShelf('rows')).toFinishAllListeners()
+
+ expect(biLogic.values.config.rows).toEqual([
+ expect.objectContaining({
+ name: '',
+ expression: '',
+ type: 'unknown',
+ source: { table: 'persons' },
+ }),
+ ])
+ expect(biLogic.values.activeExpressionEditorId).toEqual(biLogic.values.config.rows[0].id)
+ expect(logic.values.queryInput).toEqual(
+ ['SELECT', ' count(*) AS count', 'FROM persons', 'LIMIT 1000'].join('\n')
+ )
+ expect(router.values.hashParams.bi).toEqual(biLogic.values.config)
+
+ biLogic.unmount()
+ })
+
+ it('adds a removable default date filter for event data', async () => {
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ const biLogic = biEditorLogic({ tabId: TAB_ID })
+ biLogic.mount()
+
+ await expectLogic(biLogic, () => biLogic.actions.setDataSource({ table: 'events' }))
+ .toFinishAllListeners()
+ .toMatchValues({
+ config: partial({
+ source: { table: 'events' },
+ filters: [
+ partial({
+ field: partial({ expression: 'timestamp', type: 'datetime' }),
+ operator: 'last_7_days',
+ }),
+ ],
+ }),
+ })
+
+ await expectLogic(biLogic, () => biLogic.actions.removeFieldFromShelf('filters', 0)).toFinishAllListeners()
+ await expectLogic(biLogic, () => biLogic.actions.addBlankFieldToShelf('rows')).toFinishAllListeners()
+
+ expect(biLogic.values.config.filters).toEqual([])
+ expect(logic.values.queryInput).not.toContain('INTERVAL 7 DAY')
+
+ biLogic.unmount()
+ })
+ })
+
describe('source URL parameter', () => {
it('remembers endpoint source when URL sync removes search params', async () => {
logic = sqlEditorLogic({
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 4466815902f3..d199f298e10a 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -101,6 +101,7 @@ import type { DataModelingDAG, DataWarehouseSavedQueryFolder, UserType } from '.
import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'
import { validateSavedQueryName } from '../saved_queries/savedQueryNameValidation'
import { dataModelingLogic } from '../scene/dataModelingLogic'
+import { BIEditorState, parseBIEditorState } from './bi/biEditorTypes'
import { connectionSelectorLogic } from './connectionSelectorLogic'
import { draftsLogic } from './draftsLogic'
import { fixSQLErrorsLogic } from './fixSQLErrorsLogic'
@@ -246,6 +247,7 @@ export interface QueryTab {
response?: Record<string, any>
draft?: DataWarehouseSavedQueryDraft
metricName?: string
+ biEditorState?: BIEditorState
}
export type SqlEditorSource = 'insight' | 'endpoint' | 'view' | 'metric'
@@ -402,6 +404,10 @@ function getTabHash(values: sqlEditorLogicType['values']): Record<string, any> {
if (values.activeTab?.draft) {
hash['draft'] = values.activeTab.draft.id
}
+ if (values.activeTab?.biEditorState) {
+ hash['mode'] = values.activeTab.biEditorState.editorView
+ hash['bi'] = values.activeTab.biEditorState.config
+ }
return hash
}
@@ -755,8 +761,10 @@ export interface sqlEditorLogicActions {
view?: DataWarehouseSavedQuery,
insight?: QueryBasedInsightModel,
draft?: DataWarehouseSavedQueryDraft,
- metricName?: string
+ metricName?: string,
+ biEditorState?: BIEditorState
) => {
+ biEditorState: BIEditorState | undefined
draft: DataWarehouseSavedQueryDraft | undefined
insight: QueryBasedInsightModel<Node<Record<string, any>>> | undefined
metricName: string | undefined
@@ -771,15 +779,19 @@ export interface sqlEditorLogicActions {
}
editInsight: (
query: string,
- insight: QueryBasedInsightModel
+ insight: QueryBasedInsightModel,
+ biEditorState?: BIEditorState
) => {
+ biEditorState: BIEditorState | undefined
insight: QueryBasedInsightModel<Node<Record<string, any>>>
query: string
}
editView: (
query: string,
- view: DataWarehouseSavedQuery
+ view: DataWarehouseSavedQuery,
+ biEditorState?: BIEditorState
) => {
+ biEditorState: BIEditorState | undefined
query: string
view: DataWarehouseSavedQuery
}
@@ -1204,13 +1216,15 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
view?: DataWarehouseSavedQuery,
insight?: QueryBasedInsightModel,
draft?: DataWarehouseSavedQueryDraft,
- metricName?: string
+ metricName?: string,
+ biEditorState?: BIEditorState
) => ({
query,
view,
insight,
draft,
metricName,
+ biEditorState,
}),
updateTab: (tab: QueryTab) => ({ tab }),
@@ -1278,13 +1292,15 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
setViewQueryLoading: (loading: boolean) => ({ loading }),
setMaterializationModalOpen: (open: boolean) => ({ open }),
setMaterializationModalView: (view: DataWarehouseSavedQuery | null) => ({ view }),
- editView: (query: string, view: DataWarehouseSavedQuery) => ({
+ editView: (query: string, view: DataWarehouseSavedQuery, biEditorState?: BIEditorState) => ({
query,
view,
+ biEditorState,
}),
- editInsight: (query: string, insight: QueryBasedInsightModel) => ({
+ editInsight: (query: string, insight: QueryBasedInsightModel, biEditorState?: BIEditorState) => ({
query,
insight,
+ biEditorState,
}),
setLastRunQuery: (lastRunQuery: DataVisualizationNode | null) => ({
lastRunQuery,
@@ -1771,13 +1787,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
})
actions._setSuggestionPayload(null)
},
- editView: ({ query, view }) => {
- actions.createTab(query, view)
+ editView: ({ query, view, biEditorState }) => {
+ actions.createTab(query, view, undefined, undefined, undefined, biEditorState)
},
- editInsight: ({ query, insight }) => {
- actions.createTab(query, undefined, insight)
+ editInsight: ({ query, insight, biEditorState }) => {
+ actions.createTab(query, undefined, insight, undefined, undefined, biEditorState)
},
- createTab: async ({ query = '', view, insight, draft, metricName }) => {
+ createTab: async ({ query = '', view, insight, draft, metricName, biEditorState }) => {
// Use tabId to ensure each browser tab has its own unique Monaco model
const tabName = insight ? (insight.name ?? NEW_QUERY) : draft?.name || view?.name || NEW_QUERY
const tabDescription = insight?.description ?? ''
@@ -1813,6 +1829,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
sourceQuery: insightVisualizationQuery,
draft: draft,
metricName,
+ biEditorState,
})
}
if (insightVisualizationQuery) {
@@ -3207,6 +3224,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
!viewIdFromUrl &&
!insightShortIdFromUrl)
const filtersFromUrl = hasFiltersHashParam ? parseFiltersFromUrl(hashParams.filters) : undefined
+ const biEditorStateFromUrl = parseBIEditorState(hashParams.mode, hashParams.bi)
const applyFiltersFromUrl = (sourceQuery: DataVisualizationNode): DataVisualizationNode => {
if (!shouldApplyFiltersFromUrl) {
return sourceQuery
@@ -3238,6 +3256,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
!hashParams.insight &&
!hashParams.draft &&
!hashParams.output_tab &&
+ !hashParams.mode &&
+ !hashParams.bi &&
values.queryInput !== null
) {
if (shouldSyncDatabaseConnection && !values.databaseLoading) {
@@ -3307,7 +3327,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
? values.dataWarehouseSavedQueryMapById[draft.saved_query_id]
: undefined
- actions.createTab(draft.query.query, associatedView, undefined, draft)
+ actions.createTab(
+ draft.query.query,
+ associatedView,
+ undefined,
+ draft,
+ undefined,
+ biEditorStateFromUrl ?? undefined
+ )
}
return
} else if (
@@ -3350,9 +3377,16 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const queryToOpen = searchParams.open_query ? searchParams.open_query : (view.query?.query ?? '')
if (outputTabFromUrl) {
- actions.createTab(queryToOpen, view)
+ actions.createTab(
+ queryToOpen,
+ view,
+ undefined,
+ undefined,
+ undefined,
+ biEditorStateFromUrl ?? undefined
+ )
} else {
- actions.editView(queryToOpen, view)
+ actions.editView(queryToOpen, view, biEditorStateFromUrl ?? undefined)
}
actions.setViewLoading(false)
actions.setViewQueryLoading(false)
@@ -3377,7 +3411,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const shortId = insightShortIdFromUrl
if (shortId === 'new') {
// Add new blank tab
- actions.createTab()
+ actions.createTab(
+ '',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ biEditorStateFromUrl ?? undefined
+ )
tabAdded = true
router.actions.replace(urls.sqlEditor(), undefined, getTabHash(values))
return
@@ -3407,7 +3448,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
if (insightVisualizationQuery) {
actions.setSourceQuery(applyFiltersFromUrl(insightVisualizationQuery))
}
- actions.editInsight(queryToOpen, insight)
+ actions.editInsight(queryToOpen, insight, biEditorStateFromUrl ?? undefined)
if (!outputTabFromUrl) {
actions.setActiveTab(OutputTab.Visualization)
}
@@ -3449,11 +3490,25 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
)
const definition = metric.definition as Record<string, unknown> | null | undefined
const metricQuery = typeof definition?.query === 'string' ? definition.query : ''
- actions.createTab(metricQuery, undefined, undefined, undefined, metric.name)
+ actions.createTab(
+ metricQuery,
+ undefined,
+ undefined,
+ undefined,
+ metric.name,
+ biEditorStateFromUrl ?? undefined
+ )
} catch {
// Invalid name, metric not found, or no access — open an unbound empty tab
// rather than binding an update target we couldn't verify.
- actions.createTab('')
+ actions.createTab(
+ '',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ biEditorStateFromUrl ?? undefined
+ )
}
tabAdded = true
} else if (searchParams.open_query) {
@@ -3464,7 +3519,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
? toDataVisualizationNode(searchParams.open_query)
: undefined
if (openQueryNode) {
- actions.createTab(openQueryNode.source.query || '')
+ actions.createTab(
+ openQueryNode.source.query || '',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ biEditorStateFromUrl ?? undefined
+ )
actions.setSourceQuery(hasFiltersHashParam ? applyFiltersFromUrl(openQueryNode) : openQueryNode)
if (!outputTabFromUrl) {
actions.setActiveTab(OutputTab.Visualization)
@@ -3475,7 +3537,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
// kea-router also decodes numeric/JSON-shaped values; a non-node object is a
// malformed URL, so fall back to an empty query rather than "[object Object]"
actions.createTab(
- typeof searchParams.open_query === 'object' ? '' : String(searchParams.open_query)
+ typeof searchParams.open_query === 'object' ? '' : String(searchParams.open_query),
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ biEditorStateFromUrl ?? undefined
)
}
tabAdded = true
@@ -3489,10 +3556,17 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
values.queryInput !== String(hashParams.q))
) {
// kea-router decodes numeric/JSON-shaped URL values to non-strings; coerce so queryInput stays a string
- actions.createTab(String(hashParams.q))
+ actions.createTab(
+ String(hashParams.q),
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ biEditorStateFromUrl ?? undefined
+ )
tabAdded = true
} else if (values.queryInput === null) {
- actions.createTab('')
+ actions.createTab('', undefined, undefined, undefined, undefined, biEditorStateFromUrl ?? undefined)
tabAdded = true
}
}
diff --git a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts
index a8c9614160e6..103911bde0cc 100644
--- a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts
@@ -1,3 +1,4 @@
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { initKeaTests } from '~/test/init'
import { experimentsFlagCleanupTaskRetrieve } from 'products/experiments/frontend/generated/api'
@@ -18,6 +19,7 @@ describe('flagCleanupTaskLogic', () => {
})
afterEach(() => {
+ resumeKeaLoadersErrors()
jest.useRealTimers()
})
@@ -53,6 +55,7 @@ describe('flagCleanupTaskLogic', () => {
})
it('keeps polling through transient failures', async () => {
+ silenceKeaLoadersErrors()
mockRetrieve
.mockRejectedValueOnce(new Error('502'))
.mockRejectedValueOnce(new Error('timeout'))
@@ -80,6 +83,7 @@ describe('flagCleanupTaskLogic', () => {
})
it('stops polling after three consecutive failures', async () => {
+ silenceKeaLoadersErrors()
mockRetrieve.mockRejectedValue(new Error('502'))
const logic = flagCleanupTaskLogic({ experimentId: 1 })
diff --git a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
index 95ffd485a2b2..b60b3d7c31c8 100644
--- a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
+++ b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
@@ -22,7 +22,7 @@ import { NotebookPanelDropzone } from './NotebookPanelDropzone'
import { notebookPanelLogic } from './notebookPanelLogic'
export function NotebookPanel(): JSX.Element | null {
- const { selectedNotebook, droppedResource, dropProperties } = useValues(notebookPanelLogic)
+ const { selectedNotebook, droppedResource } = useValues(notebookPanelLogic)
const { selectNotebook, closeSidePanel } = useActions(notebookPanelLogic)
const { notebook } = useValues(notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover }))
const editable = !notebook?.is_template
@@ -34,7 +34,7 @@ export function NotebookPanel(): JSX.Element | null {
const contentWidthHasEffect = size === 'medium'
return (
- <div ref={ref} className={cn('NotebookPanel', 'bg-transparent')} {...dropProperties}>
+ <div ref={ref} className={cn('NotebookPanel', 'bg-transparent')}>
{!droppedResource ? (
<>
<SidePanelContentContainer>
diff --git a/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.test.ts b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.test.ts
new file mode 100644
index 000000000000..622feda69501
--- /dev/null
+++ b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.test.ts
@@ -0,0 +1,40 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { initKeaTests } from '~/test/init'
+import { SidePanelTab } from '~/types'
+
+import { notebookPanelLogic } from './notebookPanelLogic'
+
+describe('notebookPanelLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ notebookPanelLogic.mount()
+ })
+
+ it('keeps the side panel state unchanged while dragging notebook resources', async () => {
+ notebookPanelLogic.actions.startDropMode()
+ window.dispatchEvent(new MouseEvent('drag', { clientX: window.innerWidth - 10 }))
+
+ await expectLogic(sidePanelStateLogic).toMatchValues({ sidePanelOpen: false, selectedTab: null })
+
+ notebookPanelLogic.actions.endDropMode()
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Notebooks)
+ notebookPanelLogic.actions.startDropMode()
+ window.dispatchEvent(new MouseEvent('drag', { clientX: window.innerWidth - 10 }))
+
+ await expectLogic(notebookPanelLogic).toMatchValues({ dropMode: true })
+ await expectLogic(sidePanelStateLogic).toMatchValues({
+ sidePanelOpen: true,
+ selectedTab: SidePanelTab.Notebooks,
+ })
+
+ notebookPanelLogic.actions.endDropMode()
+
+ await expectLogic(notebookPanelLogic).toMatchValues({ dropMode: false })
+ await expectLogic(sidePanelStateLogic).toMatchValues({
+ sidePanelOpen: true,
+ selectedTab: SidePanelTab.Notebooks,
+ })
+ })
+})
diff --git a/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts
index 56412423abf3..1b43bf73d543 100644
--- a/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts
+++ b/frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts
@@ -1,5 +1,4 @@
-import { MakeLogicType, actions, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { HTMLProps } from 'react'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -14,7 +13,6 @@ export interface notebookPanelLogicValues {
selectedTab: SidePanelTab | null // sidePanelStateLogic
sidePanelOpen: boolean // sidePanelStateLogic
dropMode: boolean
- dropProperties: Pick<HTMLProps<HTMLDivElement>, 'onDragEnter' | 'onDragLeave' | 'style'>
droppedResource: string | NotebookNodeResource | null
selectedNotebook: string
visibility: 'hidden' | 'visible'
@@ -59,7 +57,6 @@ export interface notebookPanelLogicActions {
export interface notebookPanelLogicMeta {
__keaTypeGenInternalSelectorTypes: {
visibility: (selectedTab: SidePanelTab | null, sidePanelOpen: boolean) => 'hidden' | 'visible'
- dropProperties: (dropMode: boolean) => Pick<HTMLProps<HTMLDivElement>, 'onDragEnter' | 'onDragLeave' | 'style'>
}
}
@@ -112,40 +109,16 @@ export const notebookPanelLogic = kea<notebookPanelLogicType>([
],
})),
- selectors(({ cache, actions }) => ({
+ selectors({
visibility: [
(s) => [s.selectedTab, s.sidePanelOpen],
(selectedTab: SidePanelTab | null, sidePanelOpen: boolean): 'hidden' | 'visible' => {
return selectedTab === SidePanelTab.Notebooks && sidePanelOpen ? 'visible' : 'hidden'
},
],
+ }),
- dropProperties: [
- (s) => [s.dropMode],
- (dropMode: boolean): Pick<HTMLProps<HTMLDivElement>, 'onDragEnter' | 'onDragLeave' | 'style'> => {
- return dropMode
- ? {
- onDragEnter: () => {
- cache.dragEntercount = (cache.dragEntercount || 0) + 1
- if (cache.dragEntercount === 1) {
- actions.openSidePanel(SidePanelTab.Notebooks)
- }
- },
-
- onDragLeave: () => {
- cache.dragEntercount = (cache.dragEntercount || 0) - 1
-
- if (cache.dragEntercount <= 0) {
- cache.dragEntercount = 0
- }
- },
- }
- : {}
- },
- ],
- })),
-
- listeners(({ cache, actions, values }) => ({
+ listeners(({ actions, values }) => ({
selectNotebook: (options) => {
if (options.silent) {
return
@@ -159,56 +132,5 @@ export const notebookPanelLogic = kea<notebookPanelLogicType>([
actions.closeSidePanel()
}
},
- startDropMode: () => {
- cache.dragEntercount = 0
- cache.dragStart = null
-
- cache.initialPanelState = {
- sidePanelOpen: values.sidePanelOpen,
- selectedTab: values.selectedTab,
- }
-
- // Add drag listener using disposables
- cache.disposables.add(() => {
- const dragListener = (event: MouseEvent): void => {
- if (!cache.dragStart) {
- cache.dragStart = event.pageX
- }
-
- // The drop distance is the percentage between where the drag started and where it now is
- const distanceFromRightEdge = window.innerWidth - event.pageX
- const distanceFromDragStart = event.pageX - cache.dragStart
-
- // If we have dragged a little bit to the right, or we are dragging close to the side panel
- const shouldBeOpen = distanceFromDragStart > 50 || distanceFromRightEdge < 200
-
- if (shouldBeOpen && (!values.sidePanelOpen || values.selectedTab !== SidePanelTab.Notebooks)) {
- actions.openSidePanel(SidePanelTab.Notebooks)
- } else if (!cache.initialPanelState.sidePanelOpen && !shouldBeOpen) {
- actions.closeSidePanel()
- }
- }
- window.addEventListener('drag', dragListener)
- return () => window.removeEventListener('drag', dragListener)
- }, 'dragListener')
- },
- endDropMode: () => {
- // If we are in the notebook panel then we leave it open, otherwise we revert to the original state
- if (cache.dragEntercount <= 0) {
- if (!cache.initialPanelState.sidePanelOpen) {
- actions.closeSidePanel()
- } else {
- actions.openSidePanel(cache.initialPanelState.selectedTab)
- }
- }
- cache.disposables.dispose('dragListener')
- },
})),
-
- beforeUnmount(({ cache }) => {
- // Clean up any active drag listener if component unmounts during drag
- if (cache.dragListener) {
- window.removeEventListener('drag', cache.dragListener)
- }
- }),
])
diff --git a/products/logs/frontend/components/LogsViewer/logsExportLogic.test.ts b/products/logs/frontend/components/LogsViewer/logsExportLogic.test.ts
index 77d3467b4169..12b906968bcd 100644
--- a/products/logs/frontend/components/LogsViewer/logsExportLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/logsExportLogic.test.ts
@@ -43,13 +43,11 @@ describe('logsExportLogic', () => {
localStorage.clear()
initKeaTests()
jest.clearAllMocks()
- // logsViewerLogic fetches on mount; the automocked api.logs must resolve the
- // shapes the loaders destructure (hasMore, maxExportableLogs).
- ;(api.logs.query as jest.Mock).mockResolvedValue({ results: [], hasMore: false, maxExportableLogs: 10000 })
- ;(api.logs.sparkline as jest.Mock).mockResolvedValue([])
-
- // Mounting the viewer fires fetchLogs/fetchSparkline; the automock returns
- // undefined, which would crash the loaders.
+ ;(api.get as jest.Mock).mockResolvedValue({
+ logs_distinct_id_attribute_key: 'posthogDistinctId',
+ logs_distinct_id_attribute_keys: ['posthogDistinctId'],
+ logs_session_id_attribute_keys: ['posthogSessionId'],
+ })
;(api.logs.query as jest.Mock).mockResolvedValue({
results: [],
hasMore: false,