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 a grouped BI source picker (#111172)

Marius Andrade989b3aa105
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 8a8d8b549ce2..c4ec0d3436b5 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -12,6 +12,15 @@ The SQL editor keeps unrun edits in browser storage, scoped to the user, project
An **Edited** label marks changes to a saved view or insight. **Discard changes** restores the saved copy already loaded in memory, then refreshes it from the server. The refresh preserves edits made after discarding.
Insights can be saved or updated before running the SQL. Updating a view still requires a successful run of the current SQL so its result types match the saved query. **Continue in a notebook** is in the update button's dropdown for saved views and insights.
+## Choosing data in BI mode
+
+Clicking **BI** closes the SQL editor database sidebar; clicking **SQL** opens it again.
+The sidebar toggle remains available in both modes. **Locate** in the BI data pane is shown only while the sidebar is open.
+
+Use the table picker in the data pane to browse the same source groups and folders as the database tree.
+The selected table is highlighted; expanding a folder does not select it.
+Direct connections group tables by schema. Search matches table and folder names without changing the sidebar search.
+
## Calculated measures in BI mode
With `SQL_EDITOR_BI_MODE` enabled, select a table in the SQL editor's BI mode and choose **Add calculated measure** in the data pane.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 84ce8797ac5e..963afb4d948e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5613,13 +5613,13 @@ snapshots:
lemon-ui-lemon-toast--with-progress--light:
hash: v1.k794b7964.2dd225a8bed617fb276ea6541e0af08dfadec2b3075e0230aa66943b5ea9067f.v8ST7rAT0juXM7wcbUdq2Dz8kecpbO4rcromY2LTjPY
lemon-ui-lemon-tree--default--dark:
- hash: v1.k794b7964.71802645c8ade36774f37c73fdf79c43a632dc75882fdc92654bea8b74fea746.yUS68trt1jBQFXHLI3wGxtFDhHiPynq1yskrvf6aELY
+ hash: v1.k794b7964.06542f8a01ca6e95dac7ff1276178d1d3d13a9b16d31e9bb204f2ae9ee535b94.T3YTyqjllNl2kBm4cElNyVmzvsJaBBdEx33UeBGnrTM
lemon-ui-lemon-tree--default--light:
hash: v1.k794b7964.94c2521580a8d16eb1755d73994307e7ecc3b41a93f0b2e0176b581557cc7184.jquVojK6y6hjwz8crOojJ8IPTHMMNvxp2kONCOtwicE
lemon-ui-lemon-tree--virtualized--dark:
- hash: v1.k794b7964.a1b47a23b9c7ae02faac2055b25b1ea766c133e3bb38953a6ccd2d4264a93ec9.Gj1pAEea_XKqtzxtLL8b4zSdLOguMMEoWrzkWol0Avs
+ hash: v1.k794b7964.10f8c02f1fd1651f6d8bcc276d59a613082e5c5d4923b6e54df8419185dd18dc.BoDGbbMgGzL-EhoHi1D4ftuhLq1JuKgY2IkPY1j8QAI
lemon-ui-lemon-tree--virtualized--light:
- hash: v1.k794b7964.2b545cda72cb16b6529a4b631d3b20d9452937a2643f09f1b036ef033210eb20.lPqpWk3YzBkqDLQUmplX8cWe5iolH8nMSclSS9rax8g
+ hash: v1.k794b7964.292c0f6b4c572a8ab1f318189281e6d4c34f59b7a013138847287281404c18a2.-XLOA0wsPaDxJ6hIGAvWHxX2ahV7wwHDCPG_UKYIK50
lemon-ui-lemon-widget--actions--dark:
hash: v1.k794b7964.7487149c00f0305df0ff5457cbc5fc0280c1ab2b01cddfbe4a167b953274ca43.XtX4I0xdZdp3s6Gc9SGn9Rz9ZwH1qG3meI2N2AD9H64
lemon-ui-lemon-widget--actions--light:
@@ -9506,6 +9506,10 @@ snapshots:
hash: v1.k794b7964.25fd8a22fa490bf3e3e600a984b131b28202b8172e46e1a35e090694dfe63e2f.UBgi2bw3KLPn9F1RDJIVKYgfFlzVDD2yZj4iUPufRVA
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
hash: v1.k794b7964.66016e766d5d3b78aae28be29d15e9bbf7ebb60b48de6d488eb7b10ea4676afd.wpa1Nkk9kYDByTPyA-MjGrtArnLDfzP4S6zkO34CMfo
+ scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
+ hash: v1.k794b7964.5a7a0a5291dae3a67320c33fe0d7e087ab35dcd5738ee99f101735cd7fe6895d.v84-mZ0JtjVV_28syxCq0lC0DPMk7Z4LPSKq_seARBg
+ scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
+ hash: v1.k794b7964.1ffabd4884721dfaf6e3fea1784ac20538d1e5af30d29271b2db164f5223d706.Z0ETewXWNHoOkvasozeFiSBGEQHOoMz6ep3by86ZWTI
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
hash: v1.k794b7964.ec7208e3d9f889ee6eccaec6109093fd6ea85b10ad19f1aa4789308197f2608f.IaUpl-X0QQu76brKDTNqjxOXEgO4qro9a3NSFX-n0uw
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
@@ -9523,13 +9527,13 @@ snapshots:
scenes-app-data-warehouse-sql-editor--edited-insight--light:
hash: v1.k794b7964.436ab0db5bbe37772a43ac31f23e24089833a5b90524a01059ea0bd56004786c.ztvECim8t2GfzyU0YLjaBdofiHEvt_GJMLPUlzQq3sY
scenes-app-data-warehouse-sql-editor--edited-view--dark:
- hash: v1.k794b7964.aa0e1284b237dcedac1fe3c970e850375b9061d0c1d5b6900f9f1d5e4ba44e19.ixiPsYdLQ_wCEBrAjs99WDvEvvFxrSkXuUch-3fGWsA
+ hash: v1.k794b7964.57136a6dbeab9ac511a2a5e0c7401b23a4cb0ac00d82a2be177b84f74a60ebb0.QicPm3hXLpA9re3ShhfrqX6bKcWmuAvRBCtbRpHrSFQ
scenes-app-data-warehouse-sql-editor--edited-view--light:
- hash: v1.k794b7964.bfac44e47fb689373014487971c83c5602e18d413d1d82cfb4e3816620278373.Pu-novkcDf8tMMSmGhmQOWLz1_U5Piou5PXcppc6gHQ
+ hash: v1.k794b7964.1bada9403e11b62a50423adde53ce13fcd10a5bd6c33a210f5dd58a10a956cf8.2N9MES9JfDzATg0m-6cJnj7FWTzNt6ZlLxGqqoAI54A
scenes-app-data-warehouse-sql-editor--lazy-schema--dark:
- hash: v1.k794b7964.8c150639468430cd106d26a5e3dde526b0d08bde8d07f37527113386e022d97b.xTBWyA6WWMQjVdb8wJvusy7_4oieQVnkHe2FCJxpQHg
+ hash: v1.k794b7964.377c5cbd365fb00f334e2ad85570c373fc29c7aaddb4fc942b53081f882a02d7.EG98MhlU_8eOPCG85eUQL3egUoLrtejgaMCkD8v4BFo
scenes-app-data-warehouse-sql-editor--lazy-schema--light:
- hash: v1.k794b7964.3b4c2157445c95071aca5b730f192c94fe1c7379bbec6f9e662fb0f52c74a1cb.P6dqBWgIQEb6E9d0pr2oYfd_klhDKPyksBErJxXKTY4
+ hash: v1.k794b7964.746e808509f8aa54b1a216c485d99b2f3c85366daffc3a2c3cb48b56f8512956.Y-ehuWk2tXIBDKsbWcs5nNXWQe63faDn2JUX2wPXp5o
scenes-app-data-warehouse-sql-editor--loading-insight--dark:
hash: v1.k794b7964.c5cca89da338912886f2d329a909da87ca3ce5e6f12e0c90ee23c7c8241f768e.XfxPjuo4QbCabh0VgS40-cL0nvbKa4LIqmMHGreN0zI
scenes-app-data-warehouse-sql-editor--loading-insight--light:
@@ -11287,9 +11291,9 @@ snapshots:
scenes-app-insights-side-panel-actions--unsaved-insight--light:
hash: v1.k794b7964.d1ae4193c6ddd6ec8ec70b8181cd1fa1e33cfa0728d586423355601166b2e8b2.GFGdmioAb_Lqr7qiZik9jLMbbO6yC4abdURWyrSNeOs
scenes-app-insights-sqlboxplot--edit-options--dark:
- hash: v1.k794b7964.6b417398b1404a0c14a2c0e6a7ae811efd420da6bf480f56d3a0bda9a588d3c1.6Oi7WelFLywLJ2z7fm6LCT4et_EequF7iJtDieuFdCo
+ hash: v1.k794b7964.592c80a64be448953a2cbce7666173bb5573eac6252113280bd0be2464a75690.qoIaiLRtDr1k-UVgBSrsWeE4XJfNVuewlseXmvVN9Cg
scenes-app-insights-sqlboxplot--edit-options--light:
- hash: v1.k794b7964.da10feadfe4595c16ba229d255a5ef888da9d7e379b57d2ad10a040c4866a442._kI1fdUGl15iIDvlitIftrtd__A6tUKVt21E0Xix4Fs
+ hash: v1.k794b7964.16fb281af494452f5485f9b4ea02b1be1c97791e8b850e54f2af3dfb9382bf5b.b9EJ6KEYTbd28cG5P1DzricBJFDwYyOro4KyNACKC3A
scenes-app-insights-sqlboxplot--grouped-series--dark:
hash: v1.k794b7964.0062f9e095cb6266619d2886be6973be68c7fc906f50d8b37064390de6757656.frURXaRskPxT8wSqipNvLkFVNmgq3uiSKORwD_fLWDA
scenes-app-insights-sqlboxplot--grouped-series--light:
diff --git a/frontend/src/lib/ui/Button/ButtonPrimitives.scss b/frontend/src/lib/ui/Button/ButtonPrimitives.scss
index d6dceb5bf93c..a5694d52c891 100644
--- a/frontend/src/lib/ui/Button/ButtonPrimitives.scss
+++ b/frontend/src/lib/ui/Button/ButtonPrimitives.scss
@@ -71,7 +71,8 @@
&[data-active='true'],
&[data-current='true'],
&[data-state='open'],
- [data-state='open'] > &, // Specifically for <Link> where this attribute is applied to the parent div instead of the button
+ // Link wrappers own the open state; tree items manage selection separately from expansion.
+ [data-state='open'] > &:not([role='treeitem']),
&[data-state='checked'],
&[aria-expanded='true'],
&.button-primitive--active {
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index f5cf9fec05a0..cca88ca3506e 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -127,6 +127,7 @@ export function QueryWindow({
const { editorVimModeEnabled } = useValues(userPreferencesLogic)
const { setEditorVimModeEnabled } = useActions(userPreferencesLogic)
const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)
+ const { setDatabaseTreeCollapsed } = useActions(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
@@ -280,7 +281,10 @@ export function QueryWindow({
{mode === SQLEditorMode.FullScene && biModeFeatureEnabled ? (
<LemonSegmentedButton
value={editorView}
- onChange={setEditorView}
+ onChange={(view) => {
+ setEditorView(view)
+ setDatabaseTreeCollapsed(view === BIEditorView.BI)
+ }}
options={[
{ value: BIEditorView.SQL, label: 'SQL' },
{ value: BIEditorView.BI, label: 'BI' },
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 8a69e6a8b43b..dc37ec4465b0 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -675,3 +675,61 @@ export const LazySchema: Story = {
},
},
}
+
+export const BIDataSourcePicker: Story = {
+ ...BIModeWorksheet,
+ parameters: {
+ ...BIModeWorksheet.parameters,
+ testOptions: {
+ waitForSelector: '[data-attr="bi-editor-data-source-picker"]',
+ viewport: { width: 1280, height: 800 },
+ },
+ msw: {
+ mocks: {
+ ...BIModeWorksheet.parameters?.msw.mocks,
+ post: {
+ ...BIModeWorksheet.parameters?.msw.mocks.post,
+ '/api/environments/:team_id/query/DatabaseSchemaQuery/': {
+ tables: {
+ events: { id: 'events', name: 'events', type: 'posthog', fields: BI_EVENTS_FIELDS },
+ persons: { id: 'persons', name: 'persons', type: 'posthog', fields: {} },
+ stripe_customers: {
+ id: 'stripe_customers',
+ name: 'stripe_customers',
+ type: 'data_warehouse',
+ fields: {},
+ source: { id: 'example-stripe', source_type: 'Stripe', prefix: 'stripe_' },
+ },
+ stripe_invoices: {
+ id: 'stripe_invoices',
+ name: 'stripe_invoices',
+ type: 'data_warehouse',
+ fields: {},
+ source: { id: 'example-stripe', source_type: 'Stripe', prefix: 'stripe_' },
+ },
+ postgres_orders: {
+ id: 'postgres_orders',
+ name: 'postgres_orders',
+ type: 'data_warehouse',
+ fields: {},
+ source: { id: 'example-postgres', source_type: 'Postgres', prefix: 'postgres_' },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await waitFor(() => expect(canvasElement.querySelector('[data-attr="bi-editor-data-source"]')).toBeVisible(), {
+ timeout: 15000,
+ })
+ await userEvent.click(canvas.getByRole('button', { name: 'SQL' }))
+ await userEvent.click(canvas.getByRole('button', { name: 'BI' }))
+ await waitFor(() => expect(canvas.queryByText('Locate')).not.toBeInTheDocument())
+ await userEvent.click(canvasElement.querySelector('[data-attr="bi-editor-data-source"]')!)
+ const page = within(canvasElement.ownerDocument.body)
+ await waitFor(() => expect(page.getByRole('searchbox', { name: 'Search tables' })).toBeVisible())
+ },
+}
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx
index 2d1fdea09be8..b72695758f9e 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx
@@ -1,20 +1,16 @@
import { useActions, useValues } from 'kea'
-import { IconCalendar, IconDatabase, IconPlus } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSearchableSelect, Spinner } from '@posthog/lemon-ui'
+import { IconCalendar, IconPlus } from '@posthog/icons'
+import { LemonButton, LemonInput, Spinner } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
+import { BIDataSourcePicker } from 'products/data_warehouse/frontend/bi/BIDataSourcePicker'
+
import { editorSizingLogic } from '../../editorSizingLogic'
import { queryDatabaseLogic } from '../../sidebar/queryDatabaseLogic'
import { biEditorLogic } from '../biEditorLogic'
-import {
- BIField,
- BI_FIELD_DRAG_MIME_TYPE,
- getBIDataSourceKey,
- getBIDropTarget,
- serializeBIField,
-} from '../biEditorTypes'
+import { BIField, BI_FIELD_DRAG_MIME_TYPE, getBIDropTarget, serializeBIField } from '../biEditorTypes'
function FieldTypeGlyph({ field, measure }: { field: BIField; measure: boolean }): JSX.Element {
const glyph =
@@ -96,18 +92,15 @@ function DataPaneSection({
/** Lists the selected table's fields as dimensions and measures, ready to drag onto shelves. */
export function BIDataPane(): JSX.Element {
const {
- availableDataSources,
config,
- databaseLoading,
dataPaneFields,
dataPaneFieldsLoading,
dataPaneFieldsError,
dataPaneSearch,
filteredDataPaneFields,
- selectableDataSources,
} = useValues(biEditorLogic)
- const { editCalculatedMeasure, hydrateTableFields, setDataPaneSearch, setDataSource } = useActions(biEditorLogic)
- const { setDatabaseTreeCollapsed } = useActions(editorSizingLogic)
+ const { editCalculatedMeasure, hydrateTableFields, setDataPaneSearch } = useActions(biEditorLogic)
+ const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)
const { locateTable } = useActions(queryDatabaseLogic)
const hasFields = dataPaneFields.dimensions.length > 0 || dataPaneFields.measures.length > 0
@@ -117,53 +110,24 @@ export function BIDataPane(): JSX.Element {
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex items-center justify-between gap-1 px-2 pt-2">
<span className="text-sm font-semibold">Data</span>
- <LemonButton
- type="tertiary"
- size="xsmall"
- disabledReason={!config.source ? 'Select a data source first' : undefined}
- tooltip="Show this table in the database tree"
- onClick={() => {
- if (config.source) {
- setDatabaseTreeCollapsed(false)
- locateTable(config.source.table)
- }
- }}
- >
- Locate
- </LemonButton>
+ {!isDatabaseTreeCollapsed ? (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ disabledReason={!config.source ? 'Select a data source first' : undefined}
+ tooltip="Show this table in the database tree"
+ onClick={() => {
+ if (config.source) {
+ locateTable(config.source.table)
+ }
+ }}
+ >
+ Locate
+ </LemonButton>
+ ) : null}
</div>
<div className="flex flex-col gap-1.5 p-2">
- <LemonSearchableSelect
- value={config.source ? getBIDataSourceKey(config.source) : undefined}
- options={selectableDataSources.map((source) => ({
- value: getBIDataSourceKey(source),
- label: source.table,
- }))}
- onSelect={(sourceKey) => {
- const source = selectableDataSources.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"
- fullWidth
- truncateText={{ maxWidthClass: 'max-w-full' }}
- dropdownMaxContentWidth
- data-attr="bi-editor-data-source"
- />
+ <BIDataSourcePicker />
{config.source ? (
<LemonInput
type="search"
diff --git a/products/data_warehouse/frontend/bi/BIDataSourcePicker.tsx b/products/data_warehouse/frontend/bi/BIDataSourcePicker.tsx
new file mode 100644
index 000000000000..0a34d954224c
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/BIDataSourcePicker.tsx
@@ -0,0 +1,94 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+import { useRef } from 'react'
+
+import { IconChevronDown, IconDatabase } from '@posthog/icons'
+import { LemonButton, LemonDropdown, LemonInput, Spinner } from '@posthog/lemon-ui'
+
+import { LemonTree } from 'lib/lemon-ui/LemonTree/LemonTree'
+import { TreeNodeDisplayIcon } from 'lib/lemon-ui/LemonTree/LemonTreeUtils'
+import { biEditorLogic } from 'scenes/data-warehouse/editor/bi/biEditorLogic'
+import { getBIDataSourceKey } from 'scenes/data-warehouse/editor/bi/biEditorTypes'
+
+import { biDataSourcePickerLogic } from './biDataSourcePickerLogic'
+
+export function BIDataSourcePicker(): JSX.Element {
+ const biLogic = useMountedLogic(biEditorLogic)
+ const logic = biDataSourcePickerLogic({ tabId: biLogic.props.tabId })
+ const { config, databaseLoading, databaseLoadError, open, search, filteredTree, visibleExpandedIds } =
+ useValues(logic)
+ const { setOpen, setSearch, setExpandedIds, selectSource, refreshDatabaseSchema } = useActions(logic)
+ const scrollRef = useRef<HTMLDivElement>(null)
+
+ return (
+ <LemonDropdown
+ visible={open}
+ onVisibilityChange={setOpen}
+ closeOnClickInside={false}
+ placement="bottom-start"
+ overlay={
+ <div className="flex w-72 max-w-full flex-col gap-1" data-attr="bi-editor-data-source-picker">
+ <LemonInput
+ type="search"
+ fullWidth
+ size="small"
+ value={search}
+ onChange={setSearch}
+ placeholder="Search tables"
+ aria-label="Search tables"
+ data-attr="bi-editor-data-source-search"
+ autoFocus
+ />
+ {databaseLoading ? (
+ <div className="flex items-center gap-2 p-2 text-xs text-secondary">
+ <Spinner /> Loading tables
+ </div>
+ ) : databaseLoadError ? (
+ <div className="flex flex-col items-start gap-2 p-2 text-xs">
+ <span>Couldn't load tables.</span>
+ <LemonButton size="xsmall" type="secondary" onClick={refreshDatabaseSchema}>
+ Retry
+ </LemonButton>
+ </div>
+ ) : filteredTree.length ? (
+ <div className="max-h-96 overflow-y-auto" ref={scrollRef}>
+ <LemonTree
+ data={filteredTree}
+ virtualized
+ virtualizationScrollContainerRef={scrollRef}
+ expandedItemIds={visibleExpandedIds}
+ onSetExpandedItemIds={setExpandedIds}
+ onItemClick={(item) => item && selectSource(item.id)}
+ isItemActive={(item) =>
+ !!config.source && item.id === getBIDataSourceKey(config.source)
+ }
+ renderItemIcon={(item) => (
+ <TreeNodeDisplayIcon
+ item={item}
+ expandedItemIds={visibleExpandedIds}
+ defaultNodeIcon={<IconDatabase />}
+ />
+ )}
+ />
+ </div>
+ ) : (
+ <span className="p-2 text-xs text-secondary">
+ {search ? 'No matching tables' : 'No tables available for this connection'}
+ </span>
+ )}
+ </div>
+ }
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ fullWidth
+ icon={<IconDatabase />}
+ sideIcon={<IconChevronDown />}
+ truncate
+ data-attr="bi-editor-data-source"
+ >
+ {config.source?.table ?? 'Select a table'}
+ </LemonButton>
+ </LemonDropdown>
+ )
+}
diff --git a/products/data_warehouse/frontend/bi/biDataSourcePickerLogic.ts b/products/data_warehouse/frontend/bi/biDataSourcePickerLogic.ts
new file mode 100644
index 000000000000..146ea64d7679
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/biDataSourcePickerLogic.ts
@@ -0,0 +1,155 @@
+import {
+ MakeLogicType,
+ LogicWrapper,
+ actions,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+
+import { biEditorLogic } from 'scenes/data-warehouse/editor/bi/biEditorLogic'
+import { getBIDataSourceKey } from 'scenes/data-warehouse/editor/bi/biEditorTypes'
+import { POSTHOG_WAREHOUSE } from 'scenes/data-warehouse/editor/connectionSelectorLogic'
+import { queryDatabaseLogic } from 'scenes/data-warehouse/editor/sidebar/queryDatabaseLogic'
+
+import type { TreeDataItem } from '../../../../frontend/src/lib/lemon-ui/LemonTree/LemonTree'
+import type { BIConfig, BIDataSource } from '../../../../frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes'
+import type { ExternalDataSourceConnectionOptionApi } from '../../../warehouse_sources/frontend/generated/api.schemas'
+import { buildBIDataSourceTree, getBIDataSourceFolderIds, searchBIDataSourceTree } from './biDataSourceTree'
+
+export interface BIDataSourcePickerLogicProps {
+ tabId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDataSourcePickerLogicValues {
+ config: BIConfig // biEditorLogic
+ databaseLoading: boolean // biEditorLogic
+ selectableDataSources: BIDataSource[] // biEditorLogic
+ connectionId: string | null // queryDatabaseLogic
+ databaseLoadError: string | null // queryDatabaseLogic
+ selectedDirectSource: ExternalDataSourceConnectionOptionApi | undefined // queryDatabaseLogic
+ treeData: TreeDataItem[] // queryDatabaseLogic
+ expandedIds: string[] | null
+ filteredTree: TreeDataItem[]
+ open: boolean
+ search: string
+ sourceTree: TreeDataItem[]
+ visibleExpandedIds: string[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDataSourcePickerLogicActions {
+ setDataSource: (source: BIDataSource) => {
+ source: BIDataSource
+ } // biEditorLogic
+ refreshDatabaseSchema: () => {
+ value: true
+ } // queryDatabaseLogic
+ selectSource: (id: string) => {
+ id: string
+ }
+ setExpandedIds: (ids: string[]) => {
+ ids: string[]
+ }
+ setOpen: (open: boolean) => {
+ open: boolean
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDataSourcePickerLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ sourceTree: (
+ treeData: TreeDataItem[],
+ selectableDataSources: BIDataSource[],
+ connectionId: string | null,
+ selectedDirectSource: ExternalDataSourceConnectionOptionApi | undefined
+ ) => TreeDataItem[]
+ filteredTree: (sourceTree: TreeDataItem[], search: string) => TreeDataItem[]
+ visibleExpandedIds: (filteredTree: TreeDataItem[], search: string, expandedIds: string[] | null) => string[]
+ }
+}
+
+export type biDataSourcePickerLogicType = MakeLogicType<
+ biDataSourcePickerLogicValues,
+ biDataSourcePickerLogicActions,
+ BIDataSourcePickerLogicProps,
+ biDataSourcePickerLogicMeta
+>
+
+export const biDataSourcePickerLogic: LogicWrapper<biDataSourcePickerLogicType> = kea<biDataSourcePickerLogicType>([
+ props({} as BIDataSourcePickerLogicProps),
+ key((props) => props.tabId),
+ path((key) => ['products', 'data_warehouse', 'frontend', 'bi', 'biDataSourcePickerLogic', key]),
+ connect((props: BIDataSourcePickerLogicProps) => ({
+ values: [
+ biEditorLogic({ tabId: props.tabId }),
+ ['selectableDataSources', 'config', 'databaseLoading'],
+ queryDatabaseLogic,
+ ['treeData', 'connectionId', 'selectedDirectSource', 'databaseLoadError'],
+ ],
+ actions: [
+ biEditorLogic({ tabId: props.tabId }),
+ ['setDataSource'],
+ queryDatabaseLogic,
+ ['refreshDatabaseSchema'],
+ ],
+ })),
+ actions({
+ setOpen: (open: boolean) => ({ open }),
+ setSearch: (search: string) => ({ search }),
+ setExpandedIds: (ids: string[]) => ({ ids }),
+ selectSource: (id: string) => ({ id }),
+ }),
+ reducers({
+ open: [false, { setOpen: (_, { open }) => open }],
+ search: ['', { setSearch: (_, { search }) => search, setOpen: () => '' }],
+ expandedIds: [null as string[] | null, { setExpandedIds: (_, { ids }) => ids, setOpen: () => null }],
+ }),
+ selectors({
+ sourceTree: [
+ (s) => [s.treeData, s.selectableDataSources, s.connectionId, s.selectedDirectSource],
+ (
+ tree: TreeDataItem[],
+ sources: BIDataSource[],
+ connectionId: string | null,
+ selectedDirectSource: ExternalDataSourceConnectionOptionApi | undefined
+ ) =>
+ buildBIDataSourceTree(
+ tree,
+ sources,
+ !!connectionId && connectionId !== POSTHOG_WAREHOUSE,
+ selectedDirectSource?.schema_name,
+ connectionId
+ ),
+ ],
+ filteredTree: [
+ (s) => [s.sourceTree, s.search],
+ (tree: TreeDataItem[], search: string) => searchBIDataSourceTree(tree, search),
+ ],
+ visibleExpandedIds: [
+ (s) => [s.filteredTree, s.search, s.expandedIds],
+ (tree: TreeDataItem[], search: string, expandedIds: string[] | null): string[] =>
+ search || expandedIds === null ? getBIDataSourceFolderIds(tree) : expandedIds,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ selectSource: ({ id }) => {
+ const source = values.selectableDataSources.find((candidate) => getBIDataSourceKey(candidate) === id)
+ if (source) {
+ actions.setDataSource(source)
+ actions.setOpen(false)
+ }
+ },
+ })),
+])
diff --git a/products/data_warehouse/frontend/bi/biDataSourceTree.test.ts b/products/data_warehouse/frontend/bi/biDataSourceTree.test.ts
new file mode 100644
index 000000000000..4e25ef607a77
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/biDataSourceTree.test.ts
@@ -0,0 +1,105 @@
+import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
+import { BIDataSource, getBIDataSourceKey } from 'scenes/data-warehouse/editor/bi/biEditorTypes'
+
+import { buildBIDataSourceTree, searchBIDataSourceTree } from './biDataSourceTree'
+
+const tree: TreeDataItem[] = [
+ {
+ id: 'sources',
+ name: 'Sources',
+ record: { type: 'sources' },
+ children: [
+ {
+ id: 'postgres',
+ name: 'Postgres',
+ record: { type: 'source-folder' },
+ children: [
+ {
+ id: 'orders',
+ name: 'sales.orders',
+ record: { type: 'table' },
+ children: [{ id: 'field', name: 'sales.customers', record: { type: 'column' } }],
+ },
+ { id: 'customers', name: 'sales.customers', record: { type: 'table' } },
+ ],
+ },
+ {
+ id: 'stripe',
+ name: 'Stripe',
+ record: { type: 'source-folder' },
+ children: [{ id: 'invoices', name: 'invoices', record: { type: 'table' } }],
+ },
+ ],
+ },
+ { id: 'drafts', name: 'Drafts', children: [{ id: 'draft', name: 'draft', record: { type: 'draft' } }] },
+]
+
+const sources: BIDataSource[] = [{ table: 'sales.orders' }, { table: 'sales.customers' }, { table: 'invoices' }]
+
+describe('BI data source tree', () => {
+ it.each([
+ ['orders', ['sales.orders']],
+ [' POSTGRES ', ['sales.orders', 'sales.customers']],
+ ['missing', []],
+ ])('searches tables and ancestor folders for %s', (search, names) => {
+ const results = searchBIDataSourceTree(buildBIDataSourceTree(tree, sources, false), search)
+ expect(
+ results.flatMap(
+ (root) => root.children?.flatMap((group) => group.children?.map((leaf) => leaf.name) ?? []) ?? []
+ )
+ ).toEqual(names)
+ if (names.length) {
+ expect(results[0].name).toBe('Sources')
+ expect(results[0].children?.[0].name).toBe('Postgres')
+ }
+ })
+
+ it('keeps selectable sources as leaves and preserves a source missing from the tree', () => {
+ const results = buildBIDataSourceTree(tree, [...sources, { table: 'saved_view' }], false)
+ expect(results.map((node) => node.name)).toEqual(['Sources', 'saved_view'])
+ const tables = results[0].children!.flatMap((folder) => folder.children!)
+ expect(tables.map((node) => node.id)).toEqual(sources.map(getBIDataSourceKey))
+ expect(tables.every((node) => !node.children)).toBe(true)
+ expect(results[1].id).toBe(getBIDataSourceKey({ table: 'saved_view' }))
+ })
+
+ it('groups direct connection tables by schema without losing connection identity', () => {
+ const connectionSources = sources.map((source) => ({ ...source, connectionId: 'example-connection' }))
+ const results = buildBIDataSourceTree(tree, connectionSources, true, 'public', 'example-connection')
+ expect(results.map((node) => node.name)).toEqual(['public', 'sales'])
+ expect(results[1].children?.map((node) => [node.displayName, node.id])).toEqual([
+ ['customers', getBIDataSourceKey(connectionSources[1])],
+ ['orders', getBIDataSourceKey(connectionSources[0])],
+ ])
+ })
+
+ it('preserves a saved source from another connection with the same table name', () => {
+ const saved = { table: 'sales.orders', connectionId: 'saved-connection' }
+ const results = buildBIDataSourceTree(tree, [saved, ...sources], false)
+ expect(results[0].children![0].children![0].id).toBe(getBIDataSourceKey(sources[0]))
+ expect(results[1].id).toBe(getBIDataSourceKey(saved))
+ })
+
+ it('keeps versioned endpoints under their folder with their icon', () => {
+ const endpoint = { table: 'report_v1' }
+ const icon = 'endpoint-icon'
+ const results = buildBIDataSourceTree(
+ [
+ {
+ id: 'views',
+ name: 'Views',
+ children: [
+ { id: 'endpoint', name: 'report', icon, record: { type: 'endpoint', tableName: 'report_v1' } },
+ ],
+ },
+ ],
+ [endpoint],
+ false
+ )
+ expect(searchBIDataSourceTree(results, 'Views')).toEqual(results)
+ expect(results).toHaveLength(1)
+ expect(results[0].children).toEqual([
+ { id: getBIDataSourceKey(endpoint), name: 'report_v1', icon, record: { type: 'endpoint' } },
+ ])
+ })
+})
diff --git a/products/data_warehouse/frontend/bi/biDataSourceTree.ts b/products/data_warehouse/frontend/bi/biDataSourceTree.ts
new file mode 100644
index 000000000000..c2d7b7850888
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/biDataSourceTree.ts
@@ -0,0 +1,59 @@
+import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
+import { BIDataSource, getBIDataSourceKey } from 'scenes/data-warehouse/editor/bi/biEditorTypes'
+import { groupDirectConnectionTableNodesBySchema } from 'scenes/data-warehouse/editor/sidebar/queryDatabaseLogic'
+
+export function buildBIDataSourceTree(
+ tree: TreeDataItem[],
+ sources: BIDataSource[],
+ directConnection: boolean,
+ defaultSchemaName?: string | null,
+ connectionId?: string | null
+): TreeDataItem[] {
+ const remaining = new Map(sources.map((source) => [getBIDataSourceKey(source), source]))
+ const leaves: TreeDataItem[] = []
+ const visit = (items: TreeDataItem[]): TreeDataItem[] =>
+ items.flatMap((item) => {
+ if (['table', 'view', 'managed-view', 'view-table', 'endpoint'].includes(item.record?.type)) {
+ const tableName = item.record?.type === 'endpoint' ? item.record.tableName : item.name
+ const source = remaining.get(
+ getBIDataSourceKey({ table: tableName, connectionId: connectionId ?? undefined })
+ )
+ if (!source) {
+ return []
+ }
+ remaining.delete(getBIDataSourceKey(source))
+ const node: TreeDataItem = {
+ id: getBIDataSourceKey(source),
+ name: source.table,
+ icon: item.icon,
+ record: { type: item.record?.type },
+ }
+ leaves.push(node)
+ return [node]
+ }
+ const children = visit(item.children ?? [])
+ return children.length
+ ? [{ id: item.id, name: item.name, icon: item.icon, record: { type: item.record?.type }, children }]
+ : []
+ })
+ const grouped = visit(tree)
+ const missing = [...remaining.values()].map((source) => ({ id: getBIDataSourceKey(source), name: source.table }))
+ return directConnection
+ ? groupDirectConnectionTableNodesBySchema([...leaves, ...missing], false, defaultSchemaName)
+ : [...grouped, ...missing]
+}
+
+export function searchBIDataSourceTree(tree: TreeDataItem[], search: string): TreeDataItem[] {
+ const term = search.trim().toLocaleLowerCase()
+ return tree.flatMap((item) => {
+ if (item.name.toLocaleLowerCase().includes(term)) {
+ return [item]
+ }
+ const children = searchBIDataSourceTree(item.children ?? [], term)
+ return children.length ? [{ ...item, children }] : []
+ })
+}
+
+export function getBIDataSourceFolderIds(tree: TreeDataItem[]): string[] {
+ return tree.flatMap((item) => (item.children?.length ? [item.id, ...getBIDataSourceFolderIds(item.children)] : []))
+}