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): expand property columns in schema sidebar (#80646)

Marius Andrae50e0b326391
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx
index b3bab67b576e..1f4418d3ac2f 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.test.tsx
@@ -18,7 +18,7 @@ const cancelAnimationFrameMock = (handle: number): void => {
window.clearTimeout(handle)
}
-describe('LemonTree virtualization', () => {
+describe('LemonTree', () => {
let requestAnimationFrameSpy: jest.SpyInstance<number, [FrameRequestCallback]>
let cancelAnimationFrameSpy: jest.SpyInstance<void, [number]>
@@ -69,6 +69,18 @@ describe('LemonTree virtualization', () => {
await flushAnimationFrame()
}
+ it('renders a standalone side action without dropdown content', () => {
+ render(
+ <LemonTree
+ data={[{ id: 'properties', name: 'properties' }]}
+ itemSideAction={() => null}
+ itemSideActionButton={() => <button>Filter properties</button>}
+ />
+ )
+
+ expect(screen.getByText('Filter properties')).toBeInTheDocument()
+ })
+
it('renders only the visible window while scrolling', async () => {
const data: TreeDataItem[] = [
{
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
index 4bf742761399..c09188412c50 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
@@ -465,6 +465,40 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
)
}
+ const sideActionContent = !isEmptyFolder && size === 'default' ? itemSideAction?.(item) : undefined
+ const sideActionButton = sideActionContent !== undefined ? itemSideActionButton?.(item) : undefined
+ const sideAction =
+ sideActionContent !== undefined ? (
+ sideActionContent !== null ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ {sideActionButton ?? (
+ <ButtonPrimitive
+ iconOnly
+ isSideActionRight
+ className="
+ absolute right-0
+ opacity-0
+ group-hover/lemon-tree-button-group:opacity-100
+ z-10
+ data-[state=open]:opacity-100
+ -outline-offset-2
+ focus-visible:opacity-100
+ "
+ >
+ <IconEllipsis className="text-tertiary size-3 group-hover/lemon-tree-button-group:text-primary z-10" />
+ </ButtonPrimitive>
+ )}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent loop align="end" side="bottom" className="max-w-[250px]">
+ {sideActionContent}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ sideActionButton
+ )
+ ) : null
+
const content = (
<AccordionPrimitive.Item
value={item.id}
@@ -521,38 +555,7 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
button
)}
- {itemSideAction &&
- itemSideAction(item) !== undefined &&
- !isEmptyFolder &&
- size === 'default' && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- {itemSideActionButton?.(item) ?? (
- <ButtonPrimitive
- iconOnly
- isSideActionRight
- className="
- absolute right-0
- opacity-0
- group-hover/lemon-tree-button-group:opacity-100
- z-10
- data-[state=open]:opacity-100
- -outline-offset-2
- focus-visible:opacity-100
- "
- >
- <IconEllipsis className="text-tertiary size-3 group-hover/lemon-tree-button-group:text-primary z-10" />
- </ButtonPrimitive>
- )}
- </DropdownMenuTrigger>
-
- {!!itemSideAction(item) && (
- <DropdownMenuContent loop align="end" side="bottom" className="max-w-[250px]">
- {itemSideAction(item)}
- </DropdownMenuContent>
- )}
- </DropdownMenu>
- )}
+ {sideAction}
</ButtonGroupPrimitive>
</AccordionPrimitive.Trigger>
diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.ts
index 2cc199e0dc2c..4c101fdc2d8e 100644
--- a/frontend/src/queries/utils.ts
+++ b/frontend/src/queries/utils.ts
@@ -826,6 +826,13 @@ export function escapePropertyAsHogQLIdentifier(identifier: string): string {
if (isQuoted(identifier)) {
return identifier // This identifier is already quoted
}
+ return escapeRawPropertyAsHogQLIdentifier(identifier)
+}
+
+export function escapeRawPropertyAsHogQLIdentifier(identifier: string): string {
+ if (identifier.match(/^[A-Za-z_$][A-Za-z0-9_$]*$/)) {
+ return identifier
+ }
// Escape backslashes and control chars, then wrap; double an inner backtick (the parser rejects a backslash-escaped delimiter). The double-quote path needs no quote escaping since it is only taken when the identifier has no `"`.
const escaped = Array.from(identifier, (c) => HOGQL_IDENTIFIER_ESCAPE_MAP[c] || c).join('')
return !identifier.includes('"') ? `"${escaped}"` : `\`${escaped.replaceAll('`', '``')}\``
diff --git a/frontend/src/scenes/data-management/properties/PropertyDefinitionEditModal.test.tsx b/frontend/src/scenes/data-management/properties/PropertyDefinitionEditModal.test.tsx
new file mode 100644
index 000000000000..8a543054ef13
--- /dev/null
+++ b/frontend/src/scenes/data-management/properties/PropertyDefinitionEditModal.test.tsx
@@ -0,0 +1,49 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, within } from '@testing-library/react'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { PropertyDefinitionEditModal } from './PropertyDefinitionEditModal'
+import type { PropertyDefinitionEditModalProps } from './propertyDefinitionEditModalLogic'
+
+describe('PropertyDefinitionEditModal', () => {
+ afterEach(cleanup)
+
+ it('shows the editable property definition fields', () => {
+ useMocks({
+ get: {
+ '/api/projects/:team/tags/': [],
+ },
+ })
+ initKeaTests()
+
+ const propertyDefinition = {
+ id: 'property-id',
+ name: 'plan',
+ description: 'Billing plan',
+ tags: ['billing'],
+ property_type: 'String',
+ verified: false,
+ hidden: false,
+ } as PropertyDefinitionEditModalProps['propertyDefinition']
+
+ render(
+ <PropertyDefinitionEditModal
+ propertyDefinition={propertyDefinition}
+ onClose={jest.fn()}
+ onSave={jest.fn()}
+ />
+ )
+
+ const dialog = screen.getByRole('dialog')
+ expect(within(dialog).getByText('Edit definition')).toBeInTheDocument()
+ expect(within(dialog).getByText('plan')).toBeInTheDocument()
+ expect(within(dialog).getByText('Tags')).toBeInTheDocument()
+ expect(within(dialog).getByText('Description')).toBeInTheDocument()
+ expect(within(dialog).getByText('Status')).toBeInTheDocument()
+ expect(within(dialog).getByText('Property type')).toBeInTheDocument()
+ expect(dialog.querySelector('[data-attr="save-property-definition"]')).toHaveAttribute('aria-disabled', 'true')
+ })
+})
diff --git a/frontend/src/scenes/data-management/properties/PropertyDefinitionEditModal.tsx b/frontend/src/scenes/data-management/properties/PropertyDefinitionEditModal.tsx
new file mode 100644
index 000000000000..ca84f95dee3e
--- /dev/null
+++ b/frontend/src/scenes/data-management/properties/PropertyDefinitionEditModal.tsx
@@ -0,0 +1,129 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonButton, LemonModal, LemonSelect, LemonTag } from '@posthog/lemon-ui'
+
+import { PropertyStatusControl } from 'lib/components/DefinitionPopover/DefinitionPopoverContents'
+import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'
+
+import type { PropertyDefinitionTypeEnumApi } from '~/generated/core/api.schemas'
+import { tagsModel } from '~/models/tagsModel'
+import { isCoreFilter } from '~/taxonomy/helpers'
+
+import { PropertyDefinitionEditModalProps, propertyDefinitionEditModalLogic } from './propertyDefinitionEditModalLogic'
+
+const PROPERTY_TYPE_OPTIONS: { label: string; value: PropertyDefinitionTypeEnumApi }[] = [
+ { value: 'DateTime', label: 'DateTime' },
+ { value: 'String', label: 'String' },
+ { value: 'Numeric', label: 'Numeric' },
+ { value: 'Boolean', label: 'Boolean' },
+]
+
+export function PropertyDefinitionEditModal(props: PropertyDefinitionEditModalProps): JSX.Element {
+ const logic = propertyDefinitionEditModalLogic(props)
+ const { propertyDefinitionEditFormChanged, isPropertyDefinitionEditFormSubmitting } = useValues(logic)
+ const { closeModal, submitPropertyDefinitionEditForm } = useActions(logic)
+ const { tags, tagsLoading } = useValues(tagsModel)
+ const allowVerification = !isCoreFilter(props.propertyDefinition.name)
+
+ return (
+ <LemonModal
+ isOpen
+ title="Edit definition"
+ width={600}
+ forceAbovePopovers
+ onClose={closeModal}
+ hasUnsavedInput={propertyDefinitionEditFormChanged}
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={closeModal}
+ disabledReason={
+ isPropertyDefinitionEditFormSubmitting ? 'Saving property definition' : undefined
+ }
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={submitPropertyDefinitionEditForm}
+ loading={isPropertyDefinitionEditFormSubmitting}
+ disabledReason={!propertyDefinitionEditFormChanged ? 'No changes to save' : undefined}
+ data-attr="save-property-definition"
+ >
+ Save
+ </LemonButton>
+ </>
+ }
+ >
+ <Form
+ logic={propertyDefinitionEditModalLogic}
+ props={props}
+ formKey="propertyDefinitionEditForm"
+ className="flex flex-col gap-4"
+ >
+ <div className="flex flex-wrap items-center gap-2 text-secondary">
+ <span>Property name:</span>
+ <LemonTag className="font-mono">{props.propertyDefinition.name}</LemonTag>
+ </div>
+
+ <div className="ph-ignore-input">
+ <LemonField name="tags" label="Tags" data-attr="definition-tags">
+ {({ value, onChange }) => (
+ <ObjectTags
+ className="definition-tags"
+ saving={isPropertyDefinitionEditFormSubmitting || tagsLoading}
+ tags={value ?? []}
+ onChange={onChange}
+ tagsAvailable={tags}
+ />
+ )}
+ </LemonField>
+ </div>
+
+ <div className="ph-ignore-input">
+ <LemonField name="description" label="Description" data-attr="definition-description">
+ <LemonTextArea />
+ </LemonField>
+ </div>
+
+ <div className="ph-ignore-input">
+ <LemonField name="verified" label="Status" data-attr="definition-status">
+ {({ value: verified, onChange }) => (
+ <LemonField name="hidden">
+ {({ value: hidden, onChange: onHiddenChange }) => (
+ <PropertyStatusControl
+ isProperty
+ verified={verified}
+ hidden={hidden}
+ showHiddenOption
+ allowVerification={allowVerification}
+ onChange={({ verified: newVerified, hidden: newHidden }) => {
+ onChange(newVerified)
+ onHiddenChange(newHidden)
+ }}
+ />
+ )}
+ </LemonField>
+ )}
+ </LemonField>
+ </div>
+
+ <div className="ph-ignore-input">
+ <LemonField name="property_type" label="Property type" data-attr="property-type">
+ {({ value, onChange }) => (
+ <LemonSelect<PropertyDefinitionTypeEnumApi>
+ value={value ?? undefined}
+ onChange={onChange}
+ options={PROPERTY_TYPE_OPTIONS}
+ />
+ )}
+ </LemonField>
+ </div>
+ </Form>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/data-management/properties/propertyDefinitionEditModalLogic.test.ts b/frontend/src/scenes/data-management/properties/propertyDefinitionEditModalLogic.test.ts
new file mode 100644
index 000000000000..0b235629c055
--- /dev/null
+++ b/frontend/src/scenes/data-management/properties/propertyDefinitionEditModalLogic.test.ts
@@ -0,0 +1,59 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { PropertyDefinitionEditModalProps, propertyDefinitionEditModalLogic } from './propertyDefinitionEditModalLogic'
+
+describe('propertyDefinitionEditModalLogic', () => {
+ it('saves the editable definition fields', async () => {
+ let requestBody: unknown
+ const onClose = jest.fn()
+ const onSave = jest.fn()
+ const propertyDefinition = {
+ id: 'property-id',
+ name: 'plan',
+ description: 'Original description',
+ tags: ['billing'],
+ property_type: 'String',
+ verified: false,
+ hidden: false,
+ } as PropertyDefinitionEditModalProps['propertyDefinition']
+
+ useMocks({
+ patch: {
+ '/api/projects/:team/property_definitions/:id/': async ({ request }) => {
+ requestBody = await request.json()
+ return [200, { ...propertyDefinition, ...(requestBody as object) }]
+ },
+ },
+ })
+ initKeaTests()
+
+ const logic = propertyDefinitionEditModalLogic({ propertyDefinition, onClose, onSave })
+ logic.mount()
+ logic.actions.setPropertyDefinitionEditFormValues({
+ description: 'Used for billing reports',
+ hidden: true,
+ property_type: 'Boolean',
+ tags: ['billing', 'reporting'],
+ verified: false,
+ })
+
+ await expectLogic(logic, () => logic.actions.submitPropertyDefinitionEditForm())
+ .toDispatchActions(['submitPropertyDefinitionEditFormSuccess'])
+ .toFinishAllListeners()
+
+ expect(requestBody).toEqual({
+ description: 'Used for billing reports',
+ hidden: true,
+ property_type: 'Boolean',
+ tags: ['billing', 'reporting'],
+ verified: false,
+ })
+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining(requestBody as object))
+ expect(onClose).not.toHaveBeenCalled()
+
+ logic.unmount()
+ })
+})
diff --git a/frontend/src/scenes/data-management/properties/propertyDefinitionEditModalLogic.ts b/frontend/src/scenes/data-management/properties/propertyDefinitionEditModalLogic.ts
new file mode 100644
index 000000000000..abc8bc3aaa7a
--- /dev/null
+++ b/frontend/src/scenes/data-management/properties/propertyDefinitionEditModalLogic.ts
@@ -0,0 +1,150 @@
+import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props } from 'kea'
+import { forms } from 'kea-forms'
+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { propertyDefinitionsPartialUpdate } from '~/generated/core/api'
+import type { EnterprisePropertyDefinitionApi, PropertyDefinitionTypeEnumApi } from '~/generated/core/api.schemas'
+import { tagsModel } from '~/models/tagsModel'
+
+export interface PropertyDefinitionEditModalProps {
+ propertyDefinition: EnterprisePropertyDefinitionApi
+ onClose: () => void
+ onSave: (propertyDefinition: EnterprisePropertyDefinitionApi) => void
+}
+
+export interface PropertyDefinitionEditForm {
+ description: string
+ hidden: boolean
+ property_type: PropertyDefinitionTypeEnumApi | null
+ tags: string[]
+ verified: boolean
+}
+
+const getPropertyDefinitionEditForm = (
+ propertyDefinition: EnterprisePropertyDefinitionApi
+): PropertyDefinitionEditForm => ({
+ description: propertyDefinition.description ?? '',
+ hidden: propertyDefinition.hidden ?? false,
+ property_type: propertyDefinition.property_type || null,
+ tags: propertyDefinition.tags?.filter((tag): tag is string => typeof tag === 'string') ?? [],
+ verified: propertyDefinition.verified ?? false,
+})
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface propertyDefinitionEditModalLogicValues {
+ currentProjectId: number | string // teamLogic
+ isPropertyDefinitionEditFormSubmitting: boolean
+ isPropertyDefinitionEditFormValid: boolean
+ propertyDefinitionEditForm: PropertyDefinitionEditForm
+ propertyDefinitionEditFormAllErrors: Record<string, any>
+ propertyDefinitionEditFormChanged: boolean
+ propertyDefinitionEditFormErrors: DeepPartialMap<PropertyDefinitionEditForm, ValidationErrorType>
+ propertyDefinitionEditFormHasErrors: boolean
+ propertyDefinitionEditFormManualErrors: Record<string, any>
+ propertyDefinitionEditFormTouched: boolean
+ propertyDefinitionEditFormTouches: Record<string, boolean>
+ propertyDefinitionEditFormValidationErrors: DeepPartialMap<PropertyDefinitionEditForm, ValidationErrorType>
+ showPropertyDefinitionEditFormErrors: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface propertyDefinitionEditModalLogicActions {
+ loadTags: () => any // tagsModel
+ closeModal: () => {
+ value: true
+ }
+ resetPropertyDefinitionEditForm: (values?: PropertyDefinitionEditForm) => {
+ values?: PropertyDefinitionEditForm
+ }
+ setPropertyDefinitionEditFormManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setPropertyDefinitionEditFormValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setPropertyDefinitionEditFormValues: (values: DeepPartial<PropertyDefinitionEditForm>) => {
+ values: DeepPartial<PropertyDefinitionEditForm>
+ }
+ submitPropertyDefinitionEditForm: () => {
+ value: boolean
+ }
+ submitPropertyDefinitionEditFormFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitPropertyDefinitionEditFormRequest: (propertyDefinitionEditForm: PropertyDefinitionEditForm) => {
+ propertyDefinitionEditForm: PropertyDefinitionEditForm
+ }
+ submitPropertyDefinitionEditFormSuccess: (propertyDefinitionEditForm: PropertyDefinitionEditForm) => {
+ propertyDefinitionEditForm: PropertyDefinitionEditForm
+ }
+ touchPropertyDefinitionEditFormField: (key: string) => {
+ key: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface propertyDefinitionEditModalLogicMeta {
+ key: string
+}
+
+export type propertyDefinitionEditModalLogicType = MakeLogicType<
+ propertyDefinitionEditModalLogicValues,
+ propertyDefinitionEditModalLogicActions,
+ PropertyDefinitionEditModalProps,
+ propertyDefinitionEditModalLogicMeta
+>
+
+export const propertyDefinitionEditModalLogic = kea<propertyDefinitionEditModalLogicType>([
+ path(['scenes', 'data-management', 'properties', 'propertyDefinitionEditModalLogic']),
+ props({} as PropertyDefinitionEditModalProps),
+ key((props) => props.propertyDefinition.id),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ actions: [tagsModel, ['loadTags']],
+ })),
+ actions({
+ closeModal: true,
+ }),
+ forms(({ actions, props, values }) => ({
+ propertyDefinitionEditForm: {
+ defaults: getPropertyDefinitionEditForm(props.propertyDefinition),
+ submit: async (formValues) => {
+ try {
+ const propertyDefinition = await propertyDefinitionsPartialUpdate(
+ String(values.currentProjectId),
+ props.propertyDefinition.id,
+ formValues
+ )
+
+ actions.resetPropertyDefinitionEditForm(getPropertyDefinitionEditForm(propertyDefinition))
+ actions.loadTags()
+ lemonToast.success('Property definition saved')
+ props.onSave(propertyDefinition)
+ } catch (error: unknown) {
+ lemonToast.error('Could not save property definition. Try again.')
+ throw error
+ }
+ },
+ },
+ })),
+ listeners(({ actions, props }) => ({
+ closeModal: () => {
+ actions.resetPropertyDefinitionEditForm(getPropertyDefinitionEditForm(props.propertyDefinition))
+ props.onClose()
+ },
+ })),
+ events(({ actions }) => ({
+ afterMount: actions.loadTags,
+ })),
+])
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/PropertyDefinitionFilter.test.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/PropertyDefinitionFilter.test.tsx
new file mode 100644
index 000000000000..d04d2aa6ba90
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/PropertyDefinitionFilter.test.tsx
@@ -0,0 +1,22 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+import { PropertyDefinitionFilter } from './PropertyDefinitionFilter'
+
+describe('PropertyDefinitionFilter', () => {
+ it('closes the filter menu when Enter is pressed', async () => {
+ render(
+ <PropertyDefinitionFilter
+ propertyDefinitionKey="events:properties"
+ propertyDefinitionSearch="browser"
+ propertyDefinitionTarget={{ type: 'event' }}
+ setPropertyDefinitionSearch={jest.fn()}
+ />
+ )
+
+ fireEvent.click(screen.getByLabelText('Filter properties'))
+ const filterInput = screen.getByPlaceholderText('Filter properties')
+ fireEvent.keyDown(filterInput, { key: 'Enter' })
+
+ await waitFor(() => expect(screen.queryByPlaceholderText('Filter properties')).toBeNull())
+ })
+})
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/PropertyDefinitionFilter.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/PropertyDefinitionFilter.tsx
new file mode 100644
index 000000000000..b5f963d6ce57
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/PropertyDefinitionFilter.tsx
@@ -0,0 +1,67 @@
+import { useState } from 'react'
+
+import { IconSearch } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonMenu, LemonMenuItems } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { SidebarPropertyDefinitionTarget } from './queryDatabaseLogic'
+
+export interface PropertyDefinitionFilterProps {
+ propertyDefinitionKey: string
+ propertyDefinitionSearch: string
+ propertyDefinitionTarget: SidebarPropertyDefinitionTarget
+ setPropertyDefinitionSearch: (
+ propertyDefinitionKey: string,
+ propertyDefinitionTarget: SidebarPropertyDefinitionTarget,
+ search: string
+ ) => void
+}
+
+export const PropertyDefinitionFilter = ({
+ propertyDefinitionKey,
+ propertyDefinitionSearch,
+ propertyDefinitionTarget,
+ setPropertyDefinitionSearch,
+}: PropertyDefinitionFilterProps): JSX.Element => {
+ const [isMenuOpen, setIsMenuOpen] = useState(false)
+ const hasActiveSearch = !!propertyDefinitionSearch
+ const menuItems: LemonMenuItems = [
+ {
+ custom: true,
+ label: () => (
+ <div className="w-56 p-2" onKeyDown={(event) => event.stopPropagation()}>
+ <LemonInput
+ type="search"
+ size="small"
+ fullWidth
+ autoFocus
+ stopPropagation
+ placeholder="Filter properties"
+ value={propertyDefinitionSearch}
+ onChange={(search) =>
+ setPropertyDefinitionSearch(propertyDefinitionKey, propertyDefinitionTarget, search)
+ }
+ onPressEnter={() => setIsMenuOpen(false)}
+ />
+ </div>
+ ),
+ },
+ ]
+
+ return (
+ <LemonMenu items={menuItems} visible={isMenuOpen} onVisibilityChange={setIsMenuOpen} closeOnClickInside={false}>
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ noPadding
+ active={isMenuOpen}
+ tooltip="Filter properties"
+ aria-label="Filter properties"
+ stopPropagation
+ className={cn('absolute right-0 z-10 -outline-offset-2', hasActiveSearch && 'text-accent')}
+ icon={<IconSearch className={cn('size-3', hasActiveSearch ? 'text-accent' : 'text-tertiary')} />}
+ />
+ </LemonMenu>
+ )
+}
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 b040f901eafb..0f9b852351b5 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.test.ts
@@ -11,6 +11,15 @@ describe('QueryDatabase', () => {
['a column with no name inserts nothing', { type: 'column' }, null],
['a row that is not a column inserts nothing', { type: 'table', columnName: 'id' }, null],
['a row with no record inserts nothing', undefined, null],
+ [
+ 'a property definition inserts its fully escaped HogQL expression',
+ {
+ type: 'column',
+ columnName: 'properties.checkout.step',
+ hogqlExpression: 'properties."checkout.step"',
+ },
+ 'properties."checkout.step"',
+ ],
])('%s', (_name, record, expected) => {
expect(getColumnInsertText(record)).toEqual(expected)
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
index 93ce60111b83..ebc82ec7f047 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
@@ -38,6 +38,7 @@ 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 { PropertyDefinitionEditModal } from 'scenes/data-management/properties/PropertyDefinitionEditModal'
import { biEditorLogic } from 'scenes/data-warehouse/editor/bi/biEditorLogic'
import {
BI_FIELD_DRAG_MIME_TYPE,
@@ -66,6 +67,7 @@ import { dataWarehouseViewsLogic } from '../../saved_queries/dataWarehouseViewsL
import { TableCertificationIcon } from '../../TableCertificationBadge'
import { draftsLogic } from '../draftsLogic'
import { renderTableCount } from '../editorSceneLogic'
+import { PropertyDefinitionFilter } from './PropertyDefinitionFilter'
import { isJoined, queryDatabaseLogic } from './queryDatabaseLogic'
export function getSidebarAddJoinSourceTableName(
@@ -95,6 +97,9 @@ export function getColumnInsertText(record: Record<string, any> | undefined): st
if (record?.type !== 'column' || !record.columnName) {
return null
}
+ if (typeof record.hogqlExpression === 'string') {
+ return record.hogqlExpression
+ }
return escapeDottedHogQLIdentifier(record.columnName)
}
@@ -141,6 +146,7 @@ export const QueryDatabase = ({
highlightedDropFolderId,
highlightViewsSectionDrop,
featureFlags,
+ editingPropertyDefinition,
} = useValues(queryDatabaseLogic)
const { config: biConfig, editorView } = useValues(biEditorLogic({ tabId }))
const isBIEditor = editorView === BIEditorView.BI
@@ -159,6 +165,10 @@ export const QueryDatabase = ({
renameDraft,
openUnsavedQuery,
deleteUnsavedQuery,
+ setPropertyDefinitionSearch,
+ openPropertyDefinitionEditor,
+ closePropertyDefinitionEditor,
+ updatePropertyDefinition,
} = useActions(queryDatabaseLogic)
const {
createDataWarehouseSavedQueryFolder,
@@ -385,7 +395,7 @@ export const QueryDatabase = ({
return [...filterTreeSections(extraTreeSections, searchTerm), ...displayedTreeData]
}, [extraTreeSections, displayedTreeData, searchTerm])
- return (
+ const tree = (
<LemonTree
ref={treeRef}
data={treeData}
@@ -458,14 +468,13 @@ export const QueryDatabase = ({
connectionId && connectionId !== POSTHOG_WAREHOUSE ? connectionId : undefined,
}
: null
- const columnName =
- isColumn && typeof item.record?.columnName === 'string' ? item.record.columnName : null
+ const columnExpression = isColumn ? getColumnInsertText(item.record) : null
const biField: BIField | null =
- biFieldSource && columnName
+ biFieldSource && columnExpression
? {
- id: getBIFieldId(biFieldSource, columnName),
+ id: getBIFieldId(biFieldSource, columnExpression),
name: item.name,
- expression: columnName,
+ expression: columnExpression,
type: item.record?.field.type,
source: biFieldSource,
}
@@ -572,6 +581,26 @@ export const QueryDatabase = ({
)
}}
itemSideAction={(item) => {
+ if (item.record?.type === 'property-field') {
+ return null
+ }
+
+ if (item.record?.propertyDefinition) {
+ return (
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ openPropertyDefinitionEditor(item.record?.propertyDefinition)
+ }}
+ >
+ <ButtonPrimitive menuItem>Edit definition</ButtonPrimitive>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ )
+ }
+
const joinMenu =
item.record?.field && item.record?.table
? (() => {
@@ -1233,6 +1262,17 @@ export const QueryDatabase = ({
return undefined
}}
itemSideActionButton={(item) => {
+ if (item.record?.type === 'property-field') {
+ return (
+ <PropertyDefinitionFilter
+ propertyDefinitionKey={item.record.propertyDefinitionKey}
+ propertyDefinitionSearch={item.record.propertyDefinitionSearch ?? ''}
+ propertyDefinitionTarget={item.record.propertyDefinitionTarget}
+ setPropertyDefinitionSearch={setPropertyDefinitionSearch}
+ />
+ )
+ }
+
if (item.record?.type === 'sources') {
return (
<ButtonPrimitive
@@ -1288,6 +1328,14 @@ export const QueryDatabase = ({
return undefined
}}
renderItemIcon={(item) => {
+ if (item.record?.type === 'property-field') {
+ return (
+ <TreeNodeDisplayIcon
+ item={{ ...item, record: { ...item.record, type: 'table' } }}
+ expandedItemIds={expandedItemIds}
+ />
+ )
+ }
if (item.record?.type === 'column') {
const icon = getFieldTypeIcon(item.record.field?.type)
const savedExpression =
@@ -1313,4 +1361,17 @@ export const QueryDatabase = ({
virtualizationScrollContainerRef={virtualizationScrollContainerRef}
/>
)
+
+ return (
+ <>
+ {tree}
+ {editingPropertyDefinition ? (
+ <PropertyDefinitionEditModal
+ propertyDefinition={editingPropertyDefinition}
+ onClose={closePropertyDefinitionEditor}
+ onSave={updatePropertyDefinition}
+ />
+ ) : null}
+ </>
+ )
}
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 91391c34fe6c..70238dda8343 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
@@ -3,21 +3,226 @@ import { expectLogic } from 'kea-test-utils'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { propertyDefinitionsList } from '~/generated/core/api'
import { performQuery } from '~/queries/query'
+import type { DatabaseSchemaField } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import {
getDefaultExpandedRootIds,
getInitialExpandedFolders,
+ getSidebarPropertyDefinitionTarget,
groupDirectConnectionTableNodesBySchema,
queryDatabaseLogic,
shouldInitializeDirectConnectionExpandedFolders,
} from './queryDatabaseLogic'
jest.mock('lib/utils/newInternalTab')
+jest.mock('~/generated/core/api', () => ({
+ propertyDefinitionsList: jest.fn(),
+}))
jest.mock('~/queries/query')
+const mockPropertyDefinitionsList = propertyDefinitionsList as jest.Mock
+
+const jsonField = (name = 'properties'): DatabaseSchemaField => ({
+ name,
+ hogql_value: name,
+ type: 'json',
+ schema_valid: true,
+})
+
describe('queryDatabaseLogic', () => {
+ describe('property definition targets', () => {
+ test.each([
+ ['event properties', 'events', 'properties', jsonField(), { type: 'event' }],
+ ['AI event properties', 'ai_events', 'properties', jsonField(), { type: 'event' }],
+ ['person properties', 'persons', 'properties', jsonField(), { type: 'person' }],
+ ['person properties joined to events', 'events', 'person.properties', jsonField(), { type: 'person' }],
+ [
+ 'group properties joined to events',
+ 'events',
+ 'group_2.properties',
+ jsonField(),
+ { type: 'group', groupTypeIndex: 2 },
+ ],
+ [
+ 'physical person properties',
+ 'events',
+ 'person_properties',
+ jsonField('person_properties'),
+ { type: 'person' },
+ ],
+ ['ambiguous group properties', 'groups', 'properties', jsonField(), null],
+ ['warehouse-shaped JSON', 'events', 'metadata', jsonField('metadata'), null],
+ [
+ 'non-JSON properties',
+ 'events',
+ 'properties',
+ { ...jsonField(), type: 'string' } as DatabaseSchemaField,
+ null,
+ ],
+ ])('%s map to the stored definition type', (_name, tableName, columnPath, field, expected) => {
+ expect(getSidebarPropertyDefinitionTarget(tableName, columnPath, field)).toEqual(expected)
+ })
+ })
+
+ it('loads pre-expanded properties, paginates, and filters them', async () => {
+ initKeaTests()
+ mockPropertyDefinitionsList
+ .mockReset()
+ .mockResolvedValueOnce({
+ count: 3,
+ results: [
+ { id: 'browser', name: '$browser', property_type: 'String' },
+ {
+ id: 'quoted-property',
+ name: '"foo" OR 1=1 OR properties."foo"',
+ property_type: 'String',
+ },
+ ],
+ })
+ .mockResolvedValueOnce({
+ count: 3,
+ results: [{ id: 'checkout-step', name: 'checkout.step', property_type: 'Numeric' }],
+ })
+ .mockResolvedValueOnce({
+ count: 1,
+ results: [{ id: 'browser', name: '$browser', property_type: 'String' }],
+ })
+ const logic = queryDatabaseLogic()
+ logic.mount()
+ logic.actions.setExpandedFolders(['sources', 'property-events-properties'])
+ await expectLogic(logic, () =>
+ databaseTableListLogic.findMounted()?.actions.loadDatabaseSuccess({
+ tables: {
+ events: {
+ id: 'events',
+ name: 'events',
+ type: 'posthog',
+ fields: { properties: jsonField() },
+ },
+ },
+ joins: [],
+ })
+ ).toDispatchActions(['loadPropertyDefinitionsSuccess'])
+
+ const propertyNode = (): NonNullable<(typeof logic.values.treeData)[number]> | undefined =>
+ logic.values.treeData
+ .find((item) => item.record?.type === 'sources')
+ ?.children?.find((item) => item.name === 'PostHog')
+ ?.children?.find((item) => item.name === 'events')
+ ?.children?.find((item) => item.record?.type === 'property-field')
+
+ expect(propertyNode()?.record?.propertyDefinitionTarget).toEqual({ type: 'event' })
+ expect(mockPropertyDefinitionsList).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ limit: 25, offset: 0, type: 'event' })
+ )
+ expect(propertyNode()?.children?.map((item) => item.name)).toEqual([
+ '$browser',
+ '"foo" OR 1=1 OR properties."foo"',
+ 'Load more',
+ ])
+ expect(propertyNode()?.children?.[1].record?.hogqlExpression).toEqual(
+ 'properties.`"foo" OR 1=1 OR properties."foo"`'
+ )
+
+ await expectLogic(logic, () =>
+ propertyNode()
+ ?.children?.find((item) => item.record?.type === 'property-definitions-load-more')
+ ?.onClick?.()
+ ).toDispatchActions(['loadPropertyDefinitionsSuccess'])
+
+ expect(mockPropertyDefinitionsList).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ offset: 2, type: 'event' })
+ )
+ expect(propertyNode()?.children?.map((item) => item.name)).toEqual([
+ '$browser',
+ '"foo" OR 1=1 OR properties."foo"',
+ 'checkout.step',
+ ])
+ expect(propertyNode()?.children?.[2].record?.hogqlExpression).toEqual('properties."checkout.step"')
+
+ await expectLogic(logic, () =>
+ logic.actions.setPropertyDefinitionSearch('events:properties', { type: 'event' }, 'browser')
+ ).toDispatchActions(['loadPropertyDefinitionsSuccess'])
+
+ expect(mockPropertyDefinitionsList).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ offset: 0, search: 'browser', type: 'event' })
+ )
+ databaseTableListLogic.findMounted()?.actions.loadDatabaseSuccess({
+ tables: {
+ events: {
+ id: 'events',
+ name: 'events',
+ type: 'posthog',
+ fields: { properties: jsonField() },
+ },
+ },
+ joins: [],
+ })
+ expect(propertyNode()?.children?.map((item) => item.name)).toEqual(['$browser'])
+ expect(propertyNode()?.record?.propertyDefinitionSearch).toEqual('browser')
+
+ const browserDefinition = logic.values.propertyDefinitionLists['events:properties'].definitions[0]
+ expect(propertyNode()?.children?.[0].record?.propertyDefinition).toEqual(browserDefinition)
+
+ logic.actions.openPropertyDefinitionEditor(browserDefinition)
+ expect(logic.values.editingPropertyDefinition).toEqual(browserDefinition)
+
+ logic.actions.updatePropertyDefinition({ ...browserDefinition, property_type: 'Boolean' })
+ expect(propertyNode()?.children?.[0].record?.field.type).toEqual('boolean')
+ expect(propertyNode()?.children?.[0].record?.propertyDefinition.property_type).toEqual('Boolean')
+ expect(logic.values.editingPropertyDefinition).toBeNull()
+
+ logic.actions.updatePropertyDefinition({ ...browserDefinition, hidden: true })
+ expect(propertyNode()?.children?.map((item) => item.name)).toEqual(['No matching properties'])
+
+ logic.unmount()
+ })
+
+ it('keeps newer property results when overlapping requests resolve out of order', async () => {
+ initKeaTests()
+ let releaseStaleResponse = (): void => {}
+ const staleResponseReleased = new Promise<void>((resolve) => {
+ releaseStaleResponse = resolve
+ })
+ mockPropertyDefinitionsList
+ .mockReset()
+ .mockImplementationOnce(async () => {
+ await staleResponseReleased
+ return {
+ count: 1,
+ results: [{ id: 'stale', name: 'stale', property_type: 'String' }],
+ }
+ })
+ .mockResolvedValueOnce({
+ count: 1,
+ results: [{ id: 'fresh', name: 'fresh', property_type: 'String' }],
+ })
+ const logic = queryDatabaseLogic()
+ logic.mount()
+
+ logic.actions.loadPropertyDefinitions('events:properties', { type: 'event' }, 0)
+ await expectLogic(logic, () =>
+ logic.actions.loadPropertyDefinitions('events:properties', { type: 'event' }, 0)
+ ).toDispatchActions(['loadPropertyDefinitionsSuccess'])
+ expect(logic.values.propertyDefinitionLists['events:properties'].definitions.map(({ name }) => name)).toEqual([
+ 'fresh',
+ ])
+
+ releaseStaleResponse()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.propertyDefinitionLists['events:properties'].definitions.map(({ name }) => name)).toEqual([
+ 'fresh',
+ ])
+ logic.unmount()
+ })
+
it('groups direct connection tables into schema folders', () => {
const grouped = groupDirectConnectionTableNodesBySchema(
[
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index 9c2bf1e960c8..ed524bf2c641 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -4,6 +4,7 @@ import { subscriptions } from 'kea-subscriptions'
import {
IconBolt,
+ IconBrackets,
IconDatabase,
IconDocument,
IconEndpoints,
@@ -21,13 +22,17 @@ import { TreeItem } from 'lib/components/DatabaseTableTree/DatabaseTableTree'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTreeRef, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { uuid } from 'lib/utils/dom'
import { createFuse, IFuseOptions } from 'lib/utils/fuseSearch'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { TableFieldsStatus, databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { POSTHOG_WAREHOUSE } from 'scenes/data-warehouse/editor/connectionSelectorLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
+import { propertyDefinitionsList } from '~/generated/core/api'
+import type { EnterprisePropertyDefinitionApi, PropertyDefinitionsListType } from '~/generated/core/api.schemas'
import {
DatabaseSchemaDataWarehouseTable,
DatabaseSchemaEndpointTable,
@@ -35,6 +40,7 @@ import {
DatabaseSchemaManagedViewTable,
DatabaseSchemaTable,
} from '~/queries/schema/schema-general'
+import { escapeDottedHogQLIdentifier, escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
import {
DataWarehouseSavedQuery,
DataWarehouseSavedQueryDraft,
@@ -145,6 +151,13 @@ const MAX_FIELD_TRAVERSAL_DEPTH = 10
type FieldTraversalOptions = {
expandedLazyNodeIds?: Set<string>
+ propertyDefinitionLists?: Record<string, SidebarPropertyDefinitionList>
+ loadPropertyDefinitions?: (
+ propertyFieldKey: string,
+ target: SidebarPropertyDefinitionTarget,
+ offset: number
+ ) => void
+ allowPropertyDefinitionExpansion?: boolean
visitedColumnPaths?: Set<string>
depth?: number
hydration?: TableFieldsHydration
@@ -181,6 +194,60 @@ const getTableFieldsState = (
return 'pending'
}
+export type SidebarPropertyDefinitionTarget = {
+ type: PropertyDefinitionsListType
+ groupTypeIndex?: number
+}
+
+export type SidebarPropertyDefinitionList = {
+ activeRequestId: string | null
+ count: number
+ definitions: EnterprisePropertyDefinitionApi[]
+ error: boolean
+ loading: boolean
+ search: string
+}
+
+const PROPERTY_DEFINITIONS_PAGE_SIZE = 25
+
+export const getSidebarPropertyDefinitionTarget = (
+ tableName: string,
+ columnPath: string,
+ field: DatabaseSchemaField
+): SidebarPropertyDefinitionTarget | null => {
+ if (field.type !== 'json') {
+ return null
+ }
+
+ const pathSegments = columnPath.split('.')
+ const fieldName = pathSegments.at(-1)
+ if (fieldName !== 'properties' && fieldName !== 'person_properties') {
+ return null
+ }
+
+ if (fieldName === 'person_properties') {
+ return { type: 'person' }
+ }
+
+ const groupPathSegment = pathSegments.find((segment) => /^(?:group|goe)_[0-4]$/.test(segment))
+ if (groupPathSegment) {
+ return { type: 'group', groupTypeIndex: Number(groupPathSegment.at(-1)) }
+ }
+
+ if (
+ ['persons', 'raw_persons'].includes(tableName) ||
+ pathSegments.some((segment) => ['person', 'pdi', 'poe'].includes(segment))
+ ) {
+ return { type: 'person' }
+ }
+
+ if (['ai_events', 'events'].includes(tableName) && columnPath === 'properties') {
+ return { type: 'event' }
+ }
+
+ return null
+}
+
export type SearchTreeSourceContext = {
allPosthogTables: DatabaseSchemaTable[]
systemTables: DatabaseSchemaTable[]
@@ -309,7 +376,8 @@ const createColumnNode = (
tableName: string,
field: DatabaseSchemaField,
columnPath: string,
- isSearch = false
+ isSearch = false,
+ hogqlExpression?: string
): TreeDataItem => ({
id: `${isSearch ? 'search-' : ''}col-${tableName}-${columnPath}`,
name: field.name,
@@ -318,10 +386,166 @@ const createColumnNode = (
type: 'column',
columnName: columnPath,
field,
+ hogqlExpression,
table: tableName,
},
})
+const getPropertyDefinitionFieldType = (
+ propertyDefinition: EnterprisePropertyDefinitionApi
+): DatabaseSchemaField['type'] => {
+ switch (propertyDefinition.property_type) {
+ case 'Boolean':
+ return 'boolean'
+ case 'DateTime':
+ return 'datetime'
+ case 'Duration':
+ case 'Numeric':
+ return 'float'
+ default:
+ return 'string'
+ }
+}
+
+const createPropertyDefinitionChildren = (
+ tableName: string,
+ columnPath: string,
+ isSearch: boolean,
+ propertyFieldKey: string,
+ target: SidebarPropertyDefinitionTarget,
+ propertyDefinitionList: SidebarPropertyDefinitionList | undefined,
+ loadPropertyDefinitions: FieldTraversalOptions['loadPropertyDefinitions']
+): TreeDataItem[] => {
+ if (!propertyDefinitionList) {
+ return [
+ {
+ id: `${isSearch ? 'search-' : ''}property-${tableName}-${columnPath}-placeholder/`,
+ name: 'Loading...',
+ displayName: <>Loading...</>,
+ icon: <Spinner />,
+ disableSelect: true,
+ type: 'loading-indicator',
+ },
+ ]
+ }
+
+ const propertyNodes: TreeDataItem[] = propertyDefinitionList.definitions.map((propertyDefinition) => {
+ const propertyPath = `${columnPath}.${propertyDefinition.name}`
+ const hogqlExpression = `${escapeDottedHogQLIdentifier(columnPath)}.${escapeRawPropertyAsHogQLIdentifier(
+ propertyDefinition.name
+ )}`
+
+ const propertyNode = createColumnNode(
+ tableName,
+ {
+ id: propertyDefinition.id,
+ name: propertyDefinition.name,
+ hogql_value: propertyDefinition.name,
+ type: getPropertyDefinitionFieldType(propertyDefinition),
+ schema_valid: true,
+ },
+ propertyPath,
+ isSearch,
+ hogqlExpression
+ )
+
+ return {
+ ...propertyNode,
+ record: {
+ ...propertyNode.record,
+ propertyDefinition,
+ },
+ }
+ })
+
+ if (propertyDefinitionList.loading) {
+ propertyNodes.push({
+ id: `${isSearch ? 'search-' : ''}property-${tableName}-${columnPath}-loading/`,
+ name: 'Loading...',
+ displayName: <>Loading...</>,
+ icon: <Spinner />,
+ disableSelect: true,
+ type: 'loading-indicator',
+ })
+ } else if (propertyDefinitionList.error) {
+ propertyNodes.push(
+ {
+ id: `${isSearch ? 'search-' : ''}property-${tableName}-${columnPath}-error/`,
+ name: "Couldn't load properties",
+ displayName: <span className="text-danger">Couldn't load properties</span>,
+ icon: <IconWarning className="text-danger" />,
+ disableSelect: true,
+ type: 'node',
+ record: { type: 'property-definitions-error' },
+ },
+ {
+ id: `${isSearch ? 'search-' : ''}property-${tableName}-${columnPath}-retry/`,
+ name: 'Try again',
+ displayName: <>Try again</>,
+ icon: <IconRefresh />,
+ onClick: () => loadPropertyDefinitions?.(propertyFieldKey, target, 0),
+ record: { type: 'property-definitions-retry' },
+ }
+ )
+ } else if (propertyDefinitionList.definitions.length < propertyDefinitionList.count) {
+ propertyNodes.push({
+ id: `${isSearch ? 'search-' : ''}property-${tableName}-${columnPath}-load-more/`,
+ name: 'Load more',
+ displayName: <>Load more</>,
+ icon: <IconPlus />,
+ onClick: () =>
+ loadPropertyDefinitions?.(propertyFieldKey, target, propertyDefinitionList.definitions.length),
+ record: { type: 'property-definitions-load-more' },
+ })
+ } else if (propertyNodes.length === 0) {
+ propertyNodes.push({
+ id: `${isSearch ? 'search-' : ''}property-${tableName}-${columnPath}-empty/`,
+ name: propertyDefinitionList.search ? 'No matching properties' : 'No properties found',
+ type: 'empty-folder',
+ record: { type: 'empty-folder' },
+ })
+ }
+
+ return propertyNodes
+}
+
+const createPropertyDefinitionFieldNode = (
+ tableName: string,
+ field: DatabaseSchemaField,
+ isSearch: boolean,
+ columnPath: string,
+ target: SidebarPropertyDefinitionTarget,
+ options: FieldTraversalOptions
+): TreeDataItem => {
+ const propertyFieldKey = `${tableName}:${columnPath}`
+ const propertyDefinitionList = options.propertyDefinitionLists?.[propertyFieldKey]
+
+ return {
+ id: `${isSearch ? 'search-' : ''}property-${tableName}-${columnPath}`,
+ name: field.name,
+ type: 'node',
+ icon: <IconBrackets />,
+ record: {
+ type: 'property-field',
+ columnName: columnPath,
+ field,
+ propertyDefinitionKey: propertyFieldKey,
+ propertyDefinitionSearch: propertyDefinitionList?.search ?? '',
+ propertyDefinitionTarget: target,
+ table: tableName,
+ },
+ children: createPropertyDefinitionChildren(
+ tableName,
+ columnPath,
+ isSearch,
+ propertyFieldKey,
+ target,
+ propertyDefinitionList,
+ options.loadPropertyDefinitions
+ ),
+ }
+}
+
const createVirtualTableField = (
fieldName: string,
parentField: DatabaseSchemaField,
@@ -810,10 +1034,27 @@ const createFieldNode = (
nextVisitedColumnPaths.add(columnKey)
const nextOptions: FieldTraversalOptions = {
expandedLazyNodeIds,
+ propertyDefinitionLists: options?.propertyDefinitionLists,
+ loadPropertyDefinitions: options?.loadPropertyDefinitions,
+ allowPropertyDefinitionExpansion: options?.allowPropertyDefinitionExpansion,
visitedColumnPaths: nextVisitedColumnPaths,
depth: depth + 1,
hydration: options?.hydration,
}
+ const propertyDefinitionTarget = options?.allowPropertyDefinitionExpansion
+ ? getSidebarPropertyDefinitionTarget(tableName, columnPath, field)
+ : null
+ if (propertyDefinitionTarget) {
+ return createPropertyDefinitionFieldNode(
+ tableName,
+ field,
+ isSearch,
+ columnPath,
+ propertyDefinitionTarget,
+ nextOptions
+ )
+ }
+
if (field.type === 'virtual_table') {
const children =
field.fields
@@ -972,10 +1213,7 @@ const createTableNode = (
matches: FuseSearchMatch[] | null = null,
isSearch = false,
tableLookup?: TableLookup,
- options?: {
- expandedLazyNodeIds?: Set<string>
- hydration?: TableFieldsHydration
- }
+ options?: FieldTraversalOptions
): TreeDataItem => {
const tableId = `${isSearch ? 'search-' : ''}table-${table.name}`
const tableChildren: TreeDataItem[] = []
@@ -993,6 +1231,9 @@ const createTableNode = (
tableChildren.push(
createFieldNode(table.name, field, isSearch, field.name, tableLookup, {
expandedLazyNodeIds: options?.expandedLazyNodeIds,
+ propertyDefinitionLists: options?.propertyDefinitionLists,
+ loadPropertyDefinitions: options?.loadPropertyDefinitions,
+ allowPropertyDefinitionExpansion: table.type === 'posthog',
hydration: options?.hydration,
})
)
@@ -1217,10 +1458,7 @@ const createSourceFolderNode = (
matches: [any, FuseSearchMatch[] | null][] = [],
isSearch = false,
tableLookup?: TableLookup,
- options?: {
- expandedLazyNodeIds?: Set<string>
- hydration?: TableFieldsHydration
- }
+ options?: FieldTraversalOptions
): TreeDataItem => {
const sourceChildren: TreeDataItem[] = []
@@ -1526,6 +1764,27 @@ const findTreeItem = (items: TreeDataItem[], targetId: string): TreeDataItem | n
return path ? path[path.length - 1] : null
}
+const getUnloadedPropertyDefinitionRequest = (
+ items: TreeDataItem[],
+ targetId: string,
+ propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>
+): { propertyFieldKey: string; target: SidebarPropertyDefinitionTarget } | null => {
+ const propertyField = findTreeItem(items, targetId)
+ const propertyFieldKey = propertyField?.record?.propertyDefinitionKey
+ const target = propertyField?.record?.propertyDefinitionTarget as SidebarPropertyDefinitionTarget | undefined
+
+ if (
+ propertyField?.record?.type !== 'property-field' ||
+ typeof propertyFieldKey !== 'string' ||
+ !target ||
+ propertyDefinitionLists[propertyFieldKey]
+ ) {
+ return null
+ }
+
+ return { propertyFieldKey, target }
+}
+
const getTreeItemDataSourceName = (item: TreeDataItem): string | null => {
switch (item.record?.type) {
case 'table':
@@ -1616,12 +1875,14 @@ export interface queryDatabaseLogicValues {
joins: DataWarehouseViewLink[] // joinsLogic
joinsLoading: boolean // joinsLogic
dataWarehouseSources: PaginatedResponse<ExternalDataSource> | null // sourceManagementLogic
+ currentProjectId: number | string // teamLogic
user: UserType | null // userLogic
activeDraggedViewId: string | null
activeExpandedFolderIds: string[]
defaultExpandedRootIds: string[]
displayedTreeData: TreeDataItem[]
editingDraftId: string | null
+ editingPropertyDefinition: EnterprisePropertyDefinitionApi | null
effectiveDataWarehouseSavedQueries: DataWarehouseSavedQuery[]
expandedFolders: string[]
expandedFoldersByConnection: Record<string, string[]>
@@ -1632,6 +1893,7 @@ export interface queryDatabaseLogicValues {
highlightedDropFolderId: string | null
joinsByFieldName: Record<string, DataWarehouseViewLink>
pendingViewFolderOverrides: Record<string, string | null>
+ propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>
queryTabState: QueryTabState | null
queryTabStateLoading: boolean
relevantDataWarehouseTables: [DatabaseSchemaDataWarehouseTable, FuseSearchMatch[] | null][]
@@ -1776,6 +2038,9 @@ export interface queryDatabaseLogicActions {
clearTableToLocate: () => {
value: true
}
+ closePropertyDefinitionEditor: () => {
+ value: true
+ }
deleteUnsavedQuery: (record: Record<string, any>) => {
record: Record<string, any>
}
@@ -1813,6 +2078,44 @@ export interface queryDatabaseLogicActions {
record: Record<string, any>
}
}
+ loadPropertyDefinitions: (
+ propertyFieldKey: string,
+ target: SidebarPropertyDefinitionTarget,
+ offset: number
+ ) => {
+ offset: number
+ propertyFieldKey: string
+ requestId: string
+ target: SidebarPropertyDefinitionTarget
+ }
+ loadPropertyDefinitionsFailure: (
+ propertyFieldKey: string,
+ search: string,
+ requestId: string
+ ) => {
+ propertyFieldKey: string
+ requestId: string
+ search: string
+ }
+ loadPropertyDefinitionsSuccess: (
+ propertyFieldKey: string,
+ search: string,
+ offset: number,
+ requestId: string,
+ response: {
+ count: number
+ results: EnterprisePropertyDefinitionApi[]
+ }
+ ) => {
+ offset: number
+ propertyFieldKey: string
+ requestId: string
+ response: {
+ count: number
+ results: EnterprisePropertyDefinitionApi[]
+ }
+ search: string
+ }
loadQueryTabState: () => any
loadQueryTabStateFailure: (
error: string,
@@ -1838,6 +2141,9 @@ export interface queryDatabaseLogicActions {
dropTargetId: string | null
viewId: string
}
+ openPropertyDefinitionEditor: (propertyDefinition: EnterprisePropertyDefinitionApi) => {
+ propertyDefinition: EnterprisePropertyDefinitionApi
+ }
openUnsavedQuery: (record: Record<string, any>) => {
record: Record<string, any>
}
@@ -1874,6 +2180,15 @@ export interface queryDatabaseLogicActions {
folderId: string | null
viewId: string
}
+ setPropertyDefinitionSearch: (
+ propertyFieldKey: string,
+ target: SidebarPropertyDefinitionTarget,
+ search: string
+ ) => {
+ propertyFieldKey: string
+ search: string
+ target: SidebarPropertyDefinitionTarget
+ }
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
@@ -1896,6 +2211,9 @@ export interface queryDatabaseLogicActions {
updateDraggedViewDropTarget: (dropTargetId: string | null) => {
dropTargetId: string | null
}
+ updatePropertyDefinition: (propertyDefinition: EnterprisePropertyDefinitionApi) => {
+ propertyDefinition: EnterprisePropertyDefinitionApi
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -1971,7 +2289,8 @@ export interface queryDatabaseLogicMeta {
searchTerm: string,
featureFlags: FeatureFlagsSet,
expandedSearchFolders: string[],
- materializingViewIds: string[]
+ materializingViewIds: string[],
+ propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>
) => TreeDataItem[]
treeDataContext: (
allPosthogTables: DatabaseSchemaTable[],
@@ -1996,6 +2315,7 @@ export interface queryDatabaseLogicMeta {
queryTabState: QueryTabState | null,
expandedFolders: string[],
materializingViewIds: string[],
+ propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>,
databaseFieldsComplete: boolean,
tableFieldsStatus: TableFieldsStatus
) => TreeDataItem[]
@@ -2058,6 +2378,33 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
toggleFolderOpen: (folderId: string, isExpanded: boolean) => ({ folderId, isExpanded }),
setTreeRef: (ref: EditorSidebarTreeRef | null) => ({ ref }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
+ setPropertyDefinitionSearch: (
+ propertyFieldKey: string,
+ target: SidebarPropertyDefinitionTarget,
+ search: string
+ ) => ({ propertyFieldKey, target, search }),
+ loadPropertyDefinitions: (
+ propertyFieldKey: string,
+ target: SidebarPropertyDefinitionTarget,
+ offset: number
+ ) => ({ propertyFieldKey, target, offset, requestId: uuid() }),
+ loadPropertyDefinitionsSuccess: (
+ propertyFieldKey: string,
+ search: string,
+ offset: number,
+ requestId: string,
+ response: { count: number; results: EnterprisePropertyDefinitionApi[] }
+ ) => ({ propertyFieldKey, search, offset, requestId, response }),
+ loadPropertyDefinitionsFailure: (propertyFieldKey: string, search: string, requestId: string) => ({
+ propertyFieldKey,
+ search,
+ requestId,
+ }),
+ openPropertyDefinitionEditor: (propertyDefinition: EnterprisePropertyDefinitionApi) => ({
+ propertyDefinition,
+ }),
+ closePropertyDefinitionEditor: true,
+ updatePropertyDefinition: (propertyDefinition: EnterprisePropertyDefinitionApi) => ({ propertyDefinition }),
clearSearch: true,
clearTableToLocate: true,
locateTable: (tableName: string) => ({ tableName }),
@@ -2115,6 +2462,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
['dataWarehouseSources'],
featureFlagLogic,
['featureFlags'],
+ teamLogic,
+ ['currentProjectId'],
userLogic,
['user'],
],
@@ -2143,6 +2492,14 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
setEditingDraft: (_, { draftId }) => draftId,
},
],
+ editingPropertyDefinition: [
+ null as EnterprisePropertyDefinitionApi | null,
+ {
+ openPropertyDefinitionEditor: (_, { propertyDefinition }) => propertyDefinition,
+ closePropertyDefinitionEditor: () => null,
+ updatePropertyDefinition: () => null,
+ },
+ ],
selectedSchema: [
null as DatabaseSchemaDataWarehouseTable | DatabaseSchemaTable | DataWarehouseSavedQuery | null,
{
@@ -2195,6 +2552,107 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
clearSearch: () => '',
},
],
+ propertyDefinitionLists: [
+ {} as Record<string, SidebarPropertyDefinitionList>,
+ {
+ setPropertyDefinitionSearch: (state, { propertyFieldKey, search }) => ({
+ ...state,
+ [propertyFieldKey]: {
+ activeRequestId: null,
+ count: 0,
+ definitions: [],
+ error: false,
+ loading: true,
+ search,
+ },
+ }),
+ loadPropertyDefinitions: (state, { propertyFieldKey, offset, requestId }) => {
+ const current = state[propertyFieldKey] ?? {
+ activeRequestId: null,
+ count: 0,
+ definitions: [],
+ error: false,
+ loading: false,
+ search: '',
+ }
+
+ return {
+ ...state,
+ [propertyFieldKey]: {
+ ...current,
+ activeRequestId: requestId,
+ definitions: offset === 0 ? [] : current.definitions,
+ error: false,
+ loading: true,
+ },
+ }
+ },
+ loadPropertyDefinitionsSuccess: (state, { propertyFieldKey, search, offset, requestId, response }) => {
+ const current = state[propertyFieldKey]
+ if (!current || current.search !== search || current.activeRequestId !== requestId) {
+ return state
+ }
+
+ const definitions = offset === 0 ? response.results : [...current.definitions, ...response.results]
+ return {
+ ...state,
+ [propertyFieldKey]: {
+ ...current,
+ activeRequestId: null,
+ count: response.count,
+ definitions: Array.from(
+ new Map(definitions.map((definition) => [definition.id, definition])).values()
+ ),
+ error: false,
+ loading: false,
+ },
+ }
+ },
+ loadPropertyDefinitionsFailure: (state, { propertyFieldKey, search, requestId }) => {
+ const current = state[propertyFieldKey]
+ if (!current || current.search !== search || current.activeRequestId !== requestId) {
+ return state
+ }
+
+ return {
+ ...state,
+ [propertyFieldKey]: {
+ ...current,
+ activeRequestId: null,
+ error: true,
+ loading: false,
+ },
+ }
+ },
+ updatePropertyDefinition: (state, { propertyDefinition }) =>
+ Object.fromEntries(
+ Object.entries(state).map(([propertyFieldKey, propertyDefinitionList]) => {
+ const includesPropertyDefinition = propertyDefinitionList.definitions.some(
+ (definition) => definition.id === propertyDefinition.id
+ )
+ const definitions = propertyDefinition.hidden
+ ? propertyDefinitionList.definitions.filter(
+ (definition) => definition.id !== propertyDefinition.id
+ )
+ : propertyDefinitionList.definitions.map((definition) =>
+ definition.id === propertyDefinition.id ? propertyDefinition : definition
+ )
+
+ return [
+ propertyFieldKey,
+ {
+ ...propertyDefinitionList,
+ count:
+ propertyDefinition.hidden && includesPropertyDefinition
+ ? Math.max(0, propertyDefinitionList.count - 1)
+ : propertyDefinitionList.count,
+ definitions,
+ },
+ ]
+ })
+ ),
+ },
+ ],
syncMoreNoticeDismissed: [
false,
{ persist: true },
@@ -2280,6 +2738,28 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
updateDataWarehouseSavedQueryFailure: () => {
actions.clearPendingViewFolderOverrides()
},
+ setPropertyDefinitionSearch: async ({ propertyFieldKey, target }, breakpoint) => {
+ await breakpoint(250)
+ actions.loadPropertyDefinitions(propertyFieldKey, target, 0)
+ },
+ loadPropertyDefinitions: async ({ propertyFieldKey, target, offset, requestId }) => {
+ const search = values.propertyDefinitionLists[propertyFieldKey]?.search ?? ''
+
+ try {
+ const response = await propertyDefinitionsList(String(values.currentProjectId), {
+ exclude_hidden: true,
+ exclude_restricted: true,
+ group_type_index: target.groupTypeIndex,
+ limit: PROPERTY_DEFINITIONS_PAGE_SIZE,
+ offset,
+ search: search.trim() || undefined,
+ type: target.type,
+ })
+ actions.loadPropertyDefinitionsSuccess(propertyFieldKey, search, offset, requestId, response)
+ } catch {
+ actions.loadPropertyDefinitionsFailure(propertyFieldKey, search, requestId)
+ }
+ },
})),
listeners(({ actions, values }) => {
const revealLocatedTable = (tableName: string): void => {
@@ -2569,6 +3049,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.featureFlags,
s.expandedSearchFolders,
s.materializingViewIds,
+ s.propertyDefinitionLists,
],
(
searchTreeSourceContext: SearchTreeSourceContext,
@@ -2576,7 +3057,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
searchTerm: string,
featureFlags: FeatureFlagsSet,
expandedSearchFolders: string[],
- materializingViewIds: string[]
+ materializingViewIds: string[],
+ propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>
): TreeDataItem[] => {
if (!searchTerm) {
return []
@@ -2613,7 +3095,11 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
const expandedLazyNodeIds = new Set(expandedSearchFolders.filter(isLazyNodeId))
const sourcesChildren: TreeDataItem[] = []
const expandedIds: string[] = []
- const tableNodeOptions = { expandedLazyNodeIds }
+ const tableNodeOptions: FieldTraversalOptions = {
+ expandedLazyNodeIds,
+ propertyDefinitionLists,
+ loadPropertyDefinitions: actions.loadPropertyDefinitions,
+ }
// Add PostHog tables
if (relevantPosthogTables.length > 0) {
@@ -2811,6 +3297,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.queryTabState,
s.expandedFolders,
s.materializingViewIds,
+ s.propertyDefinitionLists,
s.databaseFieldsComplete,
s.tableFieldsStatus,
],
@@ -2826,6 +3313,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
queryTabState: QueryTabState | null,
expandedFolders: string[],
materializingViewIds: string[],
+ propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>,
databaseFieldsComplete: boolean,
tableFieldsStatus: TableFieldsStatus
): TreeDataItem[] => {
@@ -2851,7 +3339,12 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
})
const expandedLazyNodeIds = new Set(expandedFolders.filter(isLazyNodeId))
const hydration: TableFieldsHydration = { databaseFieldsComplete, tableFieldsStatus }
- const tableNodeOptions = { expandedLazyNodeIds, hydration }
+ const tableNodeOptions: FieldTraversalOptions = {
+ expandedLazyNodeIds,
+ propertyDefinitionLists,
+ loadPropertyDefinitions: actions.loadPropertyDefinitions,
+ hydration,
+ }
const schemaFailedWithNoTables =
!!databaseLoadError && !databaseLoading && Object.keys(allTablesMap).length === 0
@@ -3302,6 +3795,17 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
toggleFolderOpen: ({ folderId, isExpanded }) => {
const expandedFolders = values.searchTerm ? values.expandedSearchFolders : values.expandedFolders
+ if (!isExpanded) {
+ const request = getUnloadedPropertyDefinitionRequest(
+ values.displayedTreeData,
+ folderId,
+ values.propertyDefinitionLists
+ )
+ if (request) {
+ actions.loadPropertyDefinitions(request.propertyFieldKey, request.target, 0)
+ }
+ }
+
if (isExpanded) {
if (values.searchTerm) {
actions.setExpandedSearchFolders(expandedFolders.filter((f) => f !== folderId))
@@ -3356,10 +3860,21 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
},
})),
subscriptions(({ actions, values }) => ({
- // Hydrate fields for every visible "Loading..." placeholder. Covers expansion restored from
- // persisted state and nodes that were expanded before the shallow schema arrived; the
- // hydrate action itself dedupes tables that are already loading or settled.
displayedTreeData: (displayedTreeData: TreeDataItem[]) => {
+ for (const folderId of values.expandedItemIds) {
+ const request = getUnloadedPropertyDefinitionRequest(
+ displayedTreeData,
+ folderId,
+ values.propertyDefinitionLists
+ )
+ if (request) {
+ actions.loadPropertyDefinitions(request.propertyFieldKey, request.target, 0)
+ }
+ }
+
+ // Hydrate fields for every visible "Loading..." placeholder. Covers expansion restored from
+ // persisted state and nodes that were expanded before the shallow schema arrived; the
+ // hydrate action itself dedupes tables that are already loading or settled.
const expanded = new Set(values.searchTerm ? values.expandedSearchFolders : values.expandedFolders)
const pendingTableNames = new Set<string>()
const collect = (nodes: TreeDataItem[]): void => {