Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(bi): browse properties on related tables (#112131)

Marius Andrae291be828e4a
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 6a4675f0ab91..db037b0b9157 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -46,6 +46,8 @@ Use the table picker in the data pane to browse PostHog, warehouse, view, and sy
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.
+**Related tables** exposes existing lazy joins, virtual tables, and configured warehouse joins as expandable nodes. Fields reached through a relation keep the original source and a qualified path, so adding a customer's field to a charges worksheet does not switch tables. PostHog property fields, including `person.properties` under events, expand into searchable, paginated property definitions. Numeric definitions become measures; other definitions become dimensions. Restricted and hidden properties are excluded. Warehouse relationships use the existing join configuration; the worksheet does not create joins or infer arbitrary JSON keys.
+
## Calculated measures in BI mode
With `SQL_EDITOR_BI_MODE` enabled, open **Business intelligence**, select a table and choose **Add calculated measure** in the data pane.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 035fbe0da3a8..e4ec6590284c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9571,37 +9571,37 @@ snapshots:
scenes-app-data-warehouse-settings-schemas--multi-schema--light:
hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--dark:
- hash: v1.k794b7964.41aa02c0a9c57f31d8b4dceb3d559064a6ac666de24a627146be0ef8ca2580bb.KueO1kPhMkYNn4NBYptydJ4Dw44kbfIm6gCbcIibn2E
+ hash: v1.k794b7964.a367690805a7da1c693b589b73a8c2834446dc35e31b7b951bfc1bb308b3da7f.96-jw47y9XF2n27tdejWbZyKh7oCMNuXeG56vdP8IOI
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
- hash: v1.k794b7964.b5192f0e2350e306e6d0cc8766b43d244c9fe91eeee999e1fb97e5685dcb398a.9UQD4sOiiPThMGhxjJNZzN1ZgEmP_TBTXo0Aj-91WPY
+ hash: v1.k794b7964.d5f258bb8353baae9fe035c1ef3328abc3b5e18a3a3039020049c1ec30ac1a2f.oljSnasVuvzFxotP42I-Y4gc4Gx_hMqzns0VnD6rrco
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.97fdb4104142664ae02367e14153e70761f2e85d3b4a78be17df7eb467dfb7ac.5mHIvQIi81vR2UfkryG5TPNfYLbgBAIeTSmMQhcZddE
+ hash: v1.k794b7964.d22365ff0e0f81154761b6e1546f0740202ebbfe0822c63c38cf1a7f96cc0190.hRB57dquUAeApUp4DWQG_umChjeK4py6CBHKcc1cXx0
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.28bb2ee95b0f7344ca83f107acbc3176ef8b41bb9050abe985491c07c893a935.XoOu_8bCWvLbH1pHDCjoftd2VAO3jANSIAqtwSfryu0
+ hash: v1.k794b7964.048a336018dfc49f0c315364f24e154d45897d50ee8698a3dc51b026503ce065.sjsvVZmHY4g5D9MUjD1W4xI2zqgwDFyAYzTAihKzx3E
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.9846e12af7620a533cf6dded790e7edbd1746a8ea3688ecb7a241a05a98e48b5.RWb13JOOPQRGzSh0jzLOfma_0I7IXg6a7uZGuQCo-MA
+ hash: v1.k794b7964.93abc39bb6481de815221c0fc8e20b3388c66f90dc4bf07f9b55e5577405d671.eHsrBCsMk3JHFeHTdyRPVSnx8wGOJGaLFWD-Te-eyjQ
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.8eff07d5b039193316e4c2c88fd76261eb402a9d59501f668cb597e9c5115723.wmVx36EMRisW55v9o_8aEe1qwJh7EDvTSvY7dZWD5Tg
+ hash: v1.k794b7964.e23f5b15f3c99bf3064768fd3a048a436e9b443117cfc0a00c4d73a3f4ba2f22.nxKhSmvyyrnC7kdphG8cL24MkT9I2nGDK4vfruY2Vw0
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.50b4f288a3727642242c890e7e1a68e435ac47144545dda5b336b252ff95f164.HQC_z08nDoAjGFRajKf5aEde2BhWM8zwsHJkoPXuO9A
+ hash: v1.k794b7964.7e42ca6aa089cac5248ca5ef9344fdd857999f0719cd845ccb7ddc528f28ef15.TTDCOg_BKAoQ1kEvU5M7Awe_RT1Kep8feCfO6DNCArk
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.e4d047ec1ab8a5cdaa994a5c318b11de7320a8ce68f3a39a8c4880a3b9e77baa.07Y3AFU8UBvpaQvPxHifLqp0_Ic2aksX0h5bST9bW4Y
+ hash: v1.k794b7964.82d19296d65f2c10ad57794c4b1f93ee51f12ec1c8a1fa50d566792cf313ff60.WxJmjeoJlfxXKbIjA3n8xHc2_FhQrl4KpxnMTBDqQWI
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
hash: v1.k794b7964.a396976c1ac19d1018d181cb7a1a45b9094c1afae27b09ce5c47370dbd32719e.8W7iOXmHeV_jCUjH5EIjAg3Le0HCj-m8Uf0zVxal0ic
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
hash: v1.k794b7964.5b94e2bde6e76fca16d810c564720fbaee3d25678eff894cb660766da8f86a0b.sPgfzc_N0i2i0a80EUTnLmvKajKY4Y5V8QKI_6R0PdE
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
- hash: v1.k794b7964.ba41360a7ee0745e949e852af5672dd01da71c97ea05e1451d06c1c46cc7fd8b.C0-r7WaPwx_f3I-C4gOxHm5K6E9NX4AyiCiKkzrbWQk
+ hash: v1.k794b7964.e84877e73e6815011e2aca7c2d89844ec1fe5189781f52e440eed3c7ac78a7d5.PJfFdwO_LSix6NQonl97nVuqgHKVQORBqF3mcu8VYqg
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
- hash: v1.k794b7964.7dadf5e05828984738b4d4e381409086432b4c5c748bcc839b1da6f0b19fa2d4.KvqPBipW63BCUPdnl8dSa_TDBkWrXMDG6cLVV0UKpp8
+ hash: v1.k794b7964.bc5edcd1a6f2724d2f77bdd940b7e932a86fd463453a4faaa0a796971856244f.j7E6Gaa4jFPmH5g5mRJaKpUfiFVrjgrHhKY_xzEKzhg
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.05b26029903e019a4583d294019df0b1ec89d36a072008e2b9e8ab5212641916.ak6MRXP4V4bx5U7jk8tE_gdLLMGCbdfuch4rdGnVGM8
+ hash: v1.k794b7964.51aa1c7d5872eb708a864b09fe99c90ce0656d672ae463c4977b79f239787268.uvA-AuIOaJ8dqlKJSewyHTH7rw8Qu78Zc_P1-Esi5ok
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.a4d55c43984207e6b9d84ee4d76b63a8c18b2cf5ab1b1c00a31baf3c1cdea3fa.wjy1v69m4-V9bhC-7ZgCJB7nZoI98tyDErHNxCOAhH8
+ hash: v1.k794b7964.bc2b0e11f3a6f0b6945f8a650dc2d38e835718a6286ee76eab8ed4c5b53be026.zyksMUf8n3P02oTMl_V7_qsXoLmUE2tjS_hGbuNwlPI
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.24935f4243bb998e0429c168b387b500710ba25ef0b13b3a5b1ebbd97af3a0d1.IJ8Gx6rj4Ppt8cLxoKy0KKn6nSqiCBA4teFv30sUKPk
+ hash: v1.k794b7964.fae0f140959005592540515048113be87e37da44cc2f2bc43c235d42c029fc09.y-lrow6x4OgImDWCeHhxGFAqF9629_pTfS-sl3MadtY
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.458ee997d5f498390280ce9bc13edf52f4e2a8dbb7653e93f640487530f831da.Lu561UQbXNtDoJcg99jjZe8L-cf49MH1Ni9cY0ERg2w
+ hash: v1.k794b7964.70e1e001dd7bd0e941c854bd3202c55934bd5298dd94362ce221b2582b545a29.F5XoYtMr2_wNfTZGx7Y2rD7YTCjsSE2xZhisJ8KS1EE
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.24b439b90164ae7db044155845ca7672d56a4cba3114d585495e5dda13f24767.wjZpVrMTZpKpD3Ih75kZd7Q0gbrlPNB-GP22OYGTzZE
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
diff --git a/products/business_intelligence/frontend/BIConnections.tsx b/products/business_intelligence/frontend/BIConnections.tsx
index adda76f99689..7611ddae95ad 100644
--- a/products/business_intelligence/frontend/BIConnections.tsx
+++ b/products/business_intelligence/frontend/BIConnections.tsx
@@ -11,7 +11,7 @@ export function BIConnections(): JSX.Element {
return (
<BindLogic logic={biConnectionsLogic} props={logicProps}>
{filteredConnections.length ? (
- <div className="px-2 pb-1 pt-2 text-xs font-semibold text-secondary">Connections</div>
+ <div className="px-2 pb-1 pt-2 text-xs font-semibold text-secondary">Related tables</div>
) : null}
<BIConnectionGroup connections={filteredConnections} />
</BindLogic>
diff --git a/products/business_intelligence/frontend/BIDataPaneField.tsx b/products/business_intelligence/frontend/BIDataPaneField.tsx
new file mode 100644
index 000000000000..b845d5a306e7
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDataPaneField.tsx
@@ -0,0 +1,81 @@
+import { useActions } from 'kea'
+
+import { IconCalendar } from '@posthog/icons'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { BIField } from '~/queries/schema/schema-business-intelligence'
+
+import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
+import {
+ BI_FIELD_DRAG_MIME_TYPE,
+ getBIDropTarget,
+ serializeBIField,
+} from 'products/business_intelligence/frontend/biEditorTypes'
+
+function FieldTypeGlyph({ field, measure }: { field: BIField; measure: boolean }): JSX.Element {
+ const glyph =
+ field.type === 'date' || field.type === 'datetime' ? (
+ <IconCalendar />
+ ) : measure || ['integer', 'float', 'decimal'].includes(field.type) ? (
+ '#'
+ ) : field.type === 'boolean' ? (
+ 'T|F'
+ ) : field.type === 'json' || field.type === 'array' ? (
+ '{ }'
+ ) : (
+ 'Abc'
+ )
+ return (
+ <span
+ className={cn(
+ 'flex w-7 shrink-0 justify-center font-mono text-[10px] font-semibold',
+ measure ? 'text-success' : 'text-brand-blue'
+ )}
+ >
+ {glyph}
+ </span>
+ )
+}
+
+export function BIDataPaneField({
+ field,
+ measure,
+ path = [],
+}: {
+ field: BIField
+ measure: boolean
+ path?: string[]
+}): JSX.Element {
+ const { addFieldToShelf } = useActions(biEditorLogic)
+ const addField = (field: BIField): void => {
+ const target = getBIDropTarget(field, 'rows')
+ addFieldToShelf(target.field, target.shelf)
+ }
+ return (
+ <button
+ key={field.id}
+ type="button"
+ draggable
+ title={field.name}
+ className={cn(
+ 'flex h-6 w-full min-w-0 cursor-grab items-center gap-1 rounded px-1 text-left text-xs hover:bg-fill-highlight-100',
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent'
+ )}
+ onDragStart={(event) => {
+ event.dataTransfer.effectAllowed = 'copy'
+ event.dataTransfer.setData(BI_FIELD_DRAG_MIME_TYPE, serializeBIField(field))
+ }}
+ onDoubleClick={() => addField(field)}
+ onClick={(event) => {
+ if (event.detail === 0) {
+ addField(field)
+ }
+ }}
+ data-attr={measure ? 'bi-editor-data-pane-measure' : 'bi-editor-data-pane-dimension'}
+ >
+ <FieldTypeGlyph field={field} measure={measure} />
+ <span className="truncate">{path.length ? field.name.slice(path.join('.').length + 1) : field.name}</span>
+ </button>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIDataPaneSection.tsx b/products/business_intelligence/frontend/BIDataPaneSection.tsx
index 09d6f4511a9d..9c8bc87b3740 100644
--- a/products/business_intelligence/frontend/BIDataPaneSection.tsx
+++ b/products/business_intelligence/frontend/BIDataPaneSection.tsx
@@ -1,42 +1,11 @@
-import { useActions } from 'kea'
-
-import { IconCalendar } from '@posthog/icons'
-
-import { cn } from 'lib/utils/css-classes'
+import { useMountedLogic } from 'kea'
import { BIField } from '~/queries/schema/schema-business-intelligence'
-import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
-import {
- BI_FIELD_DRAG_MIME_TYPE,
- getBIDropTarget,
- serializeBIField,
-} from 'products/business_intelligence/frontend/biEditorTypes'
-
-function FieldTypeGlyph({ field, measure }: { field: BIField; measure: boolean }): JSX.Element {
- const glyph =
- field.type === 'date' || field.type === 'datetime' ? (
- <IconCalendar />
- ) : measure || ['integer', 'float', 'decimal'].includes(field.type) ? (
- '#'
- ) : field.type === 'boolean' ? (
- 'T|F'
- ) : field.type === 'json' || field.type === 'array' ? (
- '{ }'
- ) : (
- 'Abc'
- )
- return (
- <span
- className={cn(
- 'flex w-7 shrink-0 justify-center font-mono text-[10px] font-semibold',
- measure ? 'text-success' : 'text-brand-blue'
- )}
- >
- {glyph}
- </span>
- )
-}
+import { BIDataPaneField } from './BIDataPaneField'
+import { biEditorLogic } from './biEditorLogic'
+import { BIPropertyFieldGroup } from './BIPropertyFieldGroup'
+import { getBIPropertyTarget } from './biPropertyFields'
export function BIDataPaneSection({
title,
@@ -51,45 +20,18 @@ export function BIDataPaneSection({
emptyText: string
path?: string[]
}): JSX.Element {
- const { addFieldToShelf } = useActions(biEditorLogic)
-
- const addField = (field: BIField): void => {
- const target = getBIDropTarget(field, 'rows')
- addFieldToShelf(target.field, target.shelf)
- }
-
+ const logic = useMountedLogic(biEditorLogic)
return (
<div className="flex flex-col">
{title ? <div className="px-2 pb-1 pt-2 text-xs font-semibold text-secondary">{title}</div> : null}
{fields.length === 0 ? <span className="px-2 text-xs text-tertiary">{emptyText}</span> : null}
- {fields.map((field) => (
- <button
- key={field.id}
- type="button"
- draggable
- title={field.name}
- className={cn(
- 'flex h-6 w-full cursor-grab items-center gap-1 rounded px-1 text-left text-xs hover:bg-fill-highlight-100',
- 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent'
- )}
- onDragStart={(event) => {
- event.dataTransfer.effectAllowed = 'copy'
- event.dataTransfer.setData(BI_FIELD_DRAG_MIME_TYPE, serializeBIField(field))
- }}
- onDoubleClick={() => addField(field)}
- onClick={(event) => {
- if (event.detail === 0) {
- addField(field)
- }
- }}
- data-attr={measure ? 'bi-editor-data-pane-measure' : 'bi-editor-data-pane-dimension'}
- >
- <FieldTypeGlyph field={field} measure={measure} />
- <span className="truncate">
- {path.length ? field.name.slice(path.join('.').length + 1) : field.name}
- </span>
- </button>
- ))}
+ {fields.map((field) =>
+ getBIPropertyTarget(field) ? (
+ <BIPropertyFieldGroup key={field.id} field={field} path={path} tabId={logic.props.tabId} />
+ ) : (
+ <BIDataPaneField key={field.id} field={field} measure={measure} path={path} />
+ )
+ )}
</div>
)
}
diff --git a/products/business_intelligence/frontend/BIPropertyFieldGroup.tsx b/products/business_intelligence/frontend/BIPropertyFieldGroup.tsx
new file mode 100644
index 000000000000..42f890ec67d6
--- /dev/null
+++ b/products/business_intelligence/frontend/BIPropertyFieldGroup.tsx
@@ -0,0 +1,93 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronRight } from '@posthog/icons'
+import { LemonButton, LemonInput, Spinner } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { BIField } from '~/queries/schema/schema-business-intelligence'
+
+import { BIDataPaneField } from './BIDataPaneField'
+import { isNumericBIField } from './biEditorTypes'
+import { biPropertyFieldsLogic } from './biPropertyFieldsLogic'
+
+export function BIPropertyFieldGroup({
+ field,
+ tabId,
+ path,
+}: {
+ field: BIField
+ tabId: string
+ path: string[]
+}): JSX.Element {
+ const logic = biPropertyFieldsLogic({ field, tabId })
+ const { expanded, page, pageLoading, fields, error, search } = useValues(logic)
+ const { toggleExpanded, loadPage, setSearch } = useActions(logic)
+ return (
+ <div className="min-w-0" data-attr="bi-editor-property-group">
+ <div className="flex min-w-0 items-center">
+ <LemonButton
+ size="xxsmall"
+ type="tertiary"
+ icon={<IconChevronRight className={cn(expanded && 'rotate-90')} />}
+ aria-label={`Browse ${field.name}`}
+ aria-expanded={expanded}
+ loading={pageLoading}
+ onClick={toggleExpanded}
+ />
+ <BIDataPaneField field={{ ...field, type: 'json' }} measure={false} path={path} />
+ </div>
+ {expanded ? (
+ <div className="ml-2 min-w-0 border-l pl-1">
+ <LemonInput
+ size="small"
+ type="search"
+ value={search}
+ onChange={setSearch}
+ placeholder="Search properties"
+ aria-label={`Search ${field.name}`}
+ />
+ {fields.map((property) => (
+ <BIDataPaneField
+ key={property.id}
+ field={property}
+ measure={isNumericBIField(property)}
+ path={field.name.split('.')}
+ />
+ ))}
+ {pageLoading ? (
+ <div className="flex items-center gap-1 p-2 text-xs text-secondary">
+ <Spinner /> Loading properties
+ </div>
+ ) : null}
+ {error ? (
+ <div className="p-2 text-xs">
+ <span>Couldn't load properties.</span>
+ <LemonButton
+ size="xsmall"
+ loading={pageLoading}
+ onClick={() => loadPage({ offset: page?.results.length ?? 0 })}
+ >
+ Retry
+ </LemonButton>
+ </div>
+ ) : null}
+ {!pageLoading && !error && page && !fields.length ? (
+ <span className="block p-2 text-xs text-secondary">
+ {search ? 'No matching properties' : 'No properties found'}
+ </span>
+ ) : null}
+ {page && !error && page.results.length < page.count ? (
+ <LemonButton
+ size="xsmall"
+ loading={pageLoading}
+ onClick={() => loadPage({ offset: page.results.length })}
+ >
+ Load more
+ </LemonButton>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/business_intelligence/frontend/biConnectionTree.test.ts b/products/business_intelligence/frontend/biConnectionTree.test.ts
index 364c714d1c82..34c599998429 100644
--- a/products/business_intelligence/frontend/biConnectionTree.test.ts
+++ b/products/business_intelligence/frontend/biConnectionTree.test.ts
@@ -31,24 +31,63 @@ const tables = {
}
describe('BI connections', () => {
- it('drags nested dimensions and measures using paths from the original source', () => {
- const [person] = buildBIConnections(source, tables, ['["person"]', '["person","company"]'], {}, true)
- const [company] = person.connections
+ it.each([
+ ['events', 'person'],
+ ['stripe_charges', 'customer'],
+ ])('drags related dimensions and measures from %s through %s', (rootTable, relation) => {
+ const rootSource = { ...source, table: rootTable }
+ const warehouse = rootTable === 'stripe_charges'
+ const relatedTable = warehouse ? 'stripe_customers' : 'persons'
+ const catalog: Record<string, DatabaseSchemaTable> = {
+ ...tables,
+ [rootTable]: {
+ ...table(rootTable, [
+ field(relation, 'lazy_table', {
+ table: `\`${relatedTable}\``,
+ fields: ['email', 'lifetime_value', 'company'],
+ }),
+ ]),
+ type: warehouse ? 'data_warehouse' : 'posthog',
+ },
+ [relatedTable]: {
+ ...tables.persons,
+ name: relatedTable,
+ id: warehouse ? 'warehouse-customer-id' : 'persons',
+ type: warehouse ? 'data_warehouse' : 'posthog',
+ },
+ }
+ const [related] = buildBIConnections(
+ rootSource,
+ catalog,
+ [JSON.stringify([relation]), JSON.stringify([relation, 'company'])],
+ {},
+ true
+ )
+ const [company] = related.connections
+ expect(related.tableName).toBe(relatedTable)
expect(company.connections).toEqual([])
const dimension = company.fields.dimensions[0]
const measure = company.fields.measures[0]
- expect(dimension).toMatchObject({ name: 'person.company.name', expression: 'person.company.name', source })
- expect(measure).toMatchObject({ name: 'person.company.annual_revenue', type: 'decimal', source })
+ expect(dimension).toMatchObject({
+ name: `${relation}.company.name`,
+ expression: `${relation}.company.name`,
+ source: rootSource,
+ })
+ expect(measure).toMatchObject({
+ name: `${relation}.company.annual_revenue`,
+ type: 'decimal',
+ source: rootSource,
+ })
const value = getBIDropTarget(measure, 'rows').field as BIField
const query = buildBIQuery({
...DEFAULT_BI_CONFIG,
- source,
+ source: rootSource,
rows: [dimension],
values: [{ field: value, aggregation: 'sum' }],
})
- expect(query?.query).toContain('person.company.name')
- expect(query?.query).toContain('sum(person.company.annual_revenue)')
- expect(query?.query).toContain('FROM events')
+ expect(query?.query).toContain(`${relation}.company.name`)
+ expect(query?.query).toContain(`sum(${relation}.company.annual_revenue)`)
+ expect(query?.query).toContain(`FROM ${rootTable}`)
})
it.each(['lazy_table', 'view', 'materialized_view', 'virtual_table'] as const)(
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 4d0382e0490a..34fedfd6d634 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -347,7 +347,9 @@ export interface biEditorLogicActions {
setChartType: (chartType: ChartDisplayType) => {
chartType: ChartDisplayType
}
- setCompareFilter: (compareFilter: CompareFilter) => { compareFilter: CompareFilter }
+ setCompareFilter: (compareFilter: CompareFilter) => {
+ compareFilter: CompareFilter
+ }
setDataPaneSearch: (search: string) => {
search: string
}
diff --git a/products/business_intelligence/frontend/biPropertyFields.ts b/products/business_intelligence/frontend/biPropertyFields.ts
new file mode 100644
index 000000000000..43a31975d680
--- /dev/null
+++ b/products/business_intelligence/frontend/biPropertyFields.ts
@@ -0,0 +1,38 @@
+import { EnterprisePropertyDefinitionApi } from '~/generated/core/api.schemas'
+import { BIField } from '~/queries/schema/schema-business-intelligence'
+import { escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
+
+import {
+ getSidebarPropertyDefinitionTarget,
+ SidebarPropertyDefinitionTarget,
+} from 'products/data_warehouse/frontend/shared/propertyDefinitionTarget'
+
+export function getBIPropertyTarget(field: BIField): SidebarPropertyDefinitionTarget | null {
+ if (field.source.connectionId || !['events', 'ai_events', 'persons', 'raw_persons'].includes(field.source.table)) {
+ return null
+ }
+ return getSidebarPropertyDefinitionTarget(field.source.table, field.name, {
+ name: field.name,
+ hogql_value: field.expression,
+ schema_valid: true,
+ // Virtual tables serialize child names without their types.
+ type: field.type === 'unknown' ? 'json' : field.type,
+ })
+}
+
+export function buildBIPropertyFields(field: BIField, definitions: EnterprisePropertyDefinitionApi[]): BIField[] {
+ return definitions.map((definition) => ({
+ id: `${field.id}:${JSON.stringify(definition.name)}`,
+ name: `${field.name}.${definition.name}`,
+ expression: `${field.expression}.${escapeRawPropertyAsHogQLIdentifier(definition.name)}`,
+ source: field.source,
+ type:
+ definition.property_type === 'Boolean'
+ ? 'boolean'
+ : definition.property_type === 'DateTime'
+ ? 'datetime'
+ : ['Numeric', 'Duration'].includes(definition.property_type ?? '')
+ ? 'float'
+ : 'string',
+ }))
+}
diff --git a/products/business_intelligence/frontend/biPropertyFieldsLogic.test.ts b/products/business_intelligence/frontend/biPropertyFieldsLogic.test.ts
new file mode 100644
index 000000000000..83598e09b474
--- /dev/null
+++ b/products/business_intelligence/frontend/biPropertyFieldsLogic.test.ts
@@ -0,0 +1,96 @@
+import { expectLogic } from 'kea-test-utils'
+
+import * as api from '~/generated/core/api'
+import { EnterprisePropertyDefinitionApi } from '~/generated/core/api.schemas'
+import { BIField } from '~/queries/schema/schema-business-intelligence'
+import { initKeaTests } from '~/test/init'
+
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { getBIPropertyTarget } from './biPropertyFields'
+import { biPropertyFieldsLogic } from './biPropertyFieldsLogic'
+
+const field: BIField = {
+ id: 'events:person.properties',
+ name: 'person.properties',
+ expression: 'person.properties',
+ type: 'unknown',
+ source: { table: 'events' },
+}
+const definition = (
+ name: string,
+ property_type: EnterprisePropertyDefinitionApi['property_type'] = 'String'
+): EnterprisePropertyDefinitionApi => ({ name, property_type }) as EnterprisePropertyDefinitionApi
+
+describe('BI related properties', () => {
+ beforeEach(() => initKeaTests())
+
+ it('loads related properties on expansion, pages, searches, and keeps the root table in generated SQL', async () => {
+ const list = jest
+ .spyOn(api, 'propertyDefinitionsList')
+ .mockResolvedValue({ count: 2, results: [definition('profile.country')] })
+ const logic = biPropertyFieldsLogic({ tabId: 'properties', field })
+ logic.mount()
+ try {
+ expect(list).not.toHaveBeenCalled()
+ await expectLogic(logic, () => logic.actions.toggleExpanded()).toFinishAllListeners()
+ expect(list).toHaveBeenCalledWith(
+ '997',
+ expect.objectContaining({ type: 'person', exclude_hidden: true, exclude_restricted: true, offset: 0 })
+ )
+ expect(logic.values.fields[0]).toMatchObject({
+ expression: 'person.properties."profile.country"',
+ source: field.source,
+ type: 'string',
+ })
+ list.mockResolvedValue({ count: 2, results: [definition('annual_spend', 'Numeric')] })
+ await expectLogic(logic, () => logic.actions.loadPage({ offset: 1 })).toFinishAllListeners()
+ expect(logic.values.fields).toHaveLength(2)
+ const query = buildBIQuery({
+ ...DEFAULT_BI_CONFIG,
+ source: field.source,
+ rows: [logic.values.fields[0]],
+ values: [{ field: logic.values.fields[1], aggregation: 'sum' }],
+ })!.query
+ expect(query).toContain('person.properties."profile.country"')
+ expect(query).toContain('sum(person.properties.annual_spend)')
+ expect(query).toContain('FROM events')
+ await expectLogic(logic, () => logic.actions.setSearch('annual')).toFinishAllListeners()
+ expect(list).toHaveBeenLastCalledWith('997', expect.objectContaining({ search: 'annual', offset: 0 }))
+ expect(logic.values.fields).toHaveLength(1)
+ } finally {
+ logic.unmount()
+ list.mockRestore()
+ }
+ })
+
+ it('recovers from failed property loading without caching the failure', async () => {
+ const list = jest.spyOn(api, 'propertyDefinitionsList').mockRejectedValue(new Error('Unavailable'))
+ const logic = biPropertyFieldsLogic({ tabId: 'retry', field })
+ logic.mount()
+ try {
+ await expectLogic(logic, () => logic.actions.toggleExpanded()).toFinishAllListeners()
+ expect(logic.values.error).toBe('Unavailable')
+ expect(logic.values.pageLoading).toBe(false)
+ list.mockResolvedValue({ count: 0, results: [] })
+ await expectLogic(logic, () => logic.actions.loadPage({ offset: 0 })).toFinishAllListeners()
+ expect(logic.values.error).toBeNull()
+ expect(logic.values.page).toEqual({ count: 0, results: [] })
+ } finally {
+ logic.unmount()
+ list.mockRestore()
+ }
+ })
+
+ it.each([
+ [{ ...field, name: 'properties', type: 'json' as const }, { type: 'event' }],
+ [field, { type: 'person' }],
+ [
+ { ...field, name: 'group_0.properties' },
+ { type: 'group', groupTypeIndex: 0 },
+ ],
+ [{ ...field, source: { table: 'stripe_charges' } }, null],
+ [{ ...field, source: { table: 'events', connectionId: 'external' } }, null],
+ ])('selects property definitions for %j', (input, expected) => {
+ expect(getBIPropertyTarget(input as BIField)).toEqual(expected)
+ })
+})
diff --git a/products/business_intelligence/frontend/biPropertyFieldsLogic.ts b/products/business_intelligence/frontend/biPropertyFieldsLogic.ts
new file mode 100644
index 000000000000..3b82cbdeabee
--- /dev/null
+++ b/products/business_intelligence/frontend/biPropertyFieldsLogic.ts
@@ -0,0 +1,146 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import * as api from '~/generated/core/api'
+import { PaginatedEnterprisePropertyDefinitionListApi } from '~/generated/core/api.schemas'
+import { BIField } from '~/queries/schema/schema-business-intelligence'
+
+import { buildBIPropertyFields, getBIPropertyTarget } from './biPropertyFields'
+
+export interface BIPropertyFieldsLogicProps {
+ tabId: string
+ field: BIField
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biPropertyFieldsLogicValues {
+ currentProjectId: number | null // projectLogic
+ error: string | null
+ expanded: boolean
+ fields: BIField[]
+ page: PaginatedEnterprisePropertyDefinitionListApi | null
+ pageLoading: boolean
+ search: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biPropertyFieldsLogicActions {
+ loadPage: ({ offset }: { offset: number }) => {
+ offset: number
+ }
+ loadPageFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPageSuccess: (
+ page: PaginatedEnterprisePropertyDefinitionListApi | null,
+ payload?: {
+ offset: number
+ }
+ ) => {
+ page: PaginatedEnterprisePropertyDefinitionListApi | null
+ payload?: {
+ offset: number
+ }
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+ toggleExpanded: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biPropertyFieldsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ fields: (page: PaginatedEnterprisePropertyDefinitionListApi | null) => BIField[]
+ }
+}
+
+export type biPropertyFieldsLogicType = MakeLogicType<
+ biPropertyFieldsLogicValues,
+ biPropertyFieldsLogicActions,
+ BIPropertyFieldsLogicProps,
+ biPropertyFieldsLogicMeta
+>
+
+export const biPropertyFieldsLogic: LogicWrapper<biPropertyFieldsLogicType> = kea<biPropertyFieldsLogicType>([
+ props({} as BIPropertyFieldsLogicProps),
+ key(({ tabId, field }) => JSON.stringify([tabId, field.id])),
+ path((key) => ['products', 'business_intelligence', 'frontend', 'biPropertyFieldsLogic', key]),
+ connect({ values: [projectLogic, ['currentProjectId']] }),
+ actions({ toggleExpanded: true, setSearch: (search: string) => ({ search }) }),
+ loaders(({ props, values }) => ({
+ page: [
+ null as PaginatedEnterprisePropertyDefinitionListApi | null,
+ {
+ loadPage: async (
+ { offset }: { offset: number },
+ breakpoint
+ ): Promise<PaginatedEnterprisePropertyDefinitionListApi | null> => {
+ const target = getBIPropertyTarget(props.field)
+ if (!target || !values.currentProjectId) {
+ return null
+ }
+ if (values.search) {
+ await breakpoint(250)
+ }
+ const response = await api.propertyDefinitionsList(String(values.currentProjectId), {
+ type: target.type,
+ group_type_index: target.groupTypeIndex,
+ exclude_hidden: true,
+ exclude_restricted: true,
+ search: values.search.trim() || undefined,
+ limit: 25,
+ offset,
+ })
+ breakpoint()
+ return {
+ ...response,
+ results: [...(offset ? (values.page?.results ?? []) : []), ...response.results],
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ expanded: [false, { toggleExpanded: (expanded) => !expanded }],
+ search: ['', { setSearch: (_, { search }) => search }],
+ page: [null as PaginatedEnterprisePropertyDefinitionListApi | null, { setSearch: () => null }],
+ error: [null as string | null, { loadPage: () => null, loadPageFailure: (_, { error }) => error }],
+ }),
+ selectors(({ props }) => ({
+ fields: [
+ (s) => [s.page],
+ (page: PaginatedEnterprisePropertyDefinitionListApi | null): BIField[] =>
+ buildBIPropertyFields(props.field, page?.results ?? []),
+ ],
+ })),
+ listeners(({ actions, values }) => ({
+ toggleExpanded: () => {
+ if (values.expanded && !values.page && !values.pageLoading) {
+ actions.loadPage({ offset: 0 })
+ }
+ },
+ setSearch: () => actions.loadPage({ offset: 0 }),
+ })),
+])