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(data-warehouse): sentence-style join editor with match preview (#75566)

Thiago Salvatore0483378c5ee3
diff --git a/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx b/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx
index dae542748bf7..ebccce3ee144 100644
--- a/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx
+++ b/frontend/src/lib/components/HogQLDropdown/HogQLDropdown.tsx
@@ -13,11 +13,13 @@ export const HogQLDropdown = ({
tableName,
hogQLEditorPlaceholder,
className = '',
+ size,
}: {
hogQLValue: string
tableName: string
className?: string
hogQLEditorPlaceholder?: string
+ size?: 'small' | 'medium'
onHogQLValueChange: (hogQLValue: string) => void
}): JSX.Element => {
const [isHogQLDropdownVisible, setIsHogQLDropdownVisible] = useState(false)
@@ -46,6 +48,7 @@ export const HogQLDropdown = ({
<LemonButton
fullWidth
type="secondary"
+ size={size}
onClick={() => setIsHogQLDropdownVisible(!isHogQLDropdownVisible)}
>
<code>{hogQLValue}</code>
diff --git a/frontend/src/scenes/data-warehouse/TableCombobox.tsx b/frontend/src/scenes/data-warehouse/TableCombobox.tsx
new file mode 100644
index 000000000000..aa0239046954
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/TableCombobox.tsx
@@ -0,0 +1,84 @@
+import { useRef, useState } from 'react'
+
+import {
+ Button,
+ Combobox,
+ ComboboxCollection,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxGroup,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxLabel,
+ ComboboxList,
+ ComboboxTrigger,
+} from '@posthog/quill'
+
+import { TableOptionGroup } from './viewLinkLogic'
+
+export interface TableComboboxProps {
+ groups: TableOptionGroup[]
+ value: string | null
+ onChange: (value: string) => void
+ placeholder?: string
+ 'aria-label': string
+}
+
+export function TableCombobox({
+ groups,
+ value,
+ onChange,
+ placeholder = 'Select a table',
+ 'aria-label': ariaLabel,
+}: TableComboboxProps): JSX.Element {
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ const [open, setOpen] = useState(false)
+
+ return (
+ <Combobox
+ items={groups}
+ value={value || null}
+ onValueChange={(next: string | null) => {
+ if (next) {
+ onChange(next)
+ }
+ }}
+ open={open}
+ onOpenChange={setOpen}
+ >
+ <ComboboxTrigger
+ render={
+ <Button
+ ref={triggerRef}
+ variant="outline"
+ size="sm"
+ // h-8 matches the LemonSelect/LemonSegmentedButton "small" height so the
+ // sentence controls line up.
+ className="h-8 max-w-80"
+ aria-label={ariaLabel}
+ >
+ <span className="min-w-0 truncate">{value || placeholder}</span>
+ </Button>
+ }
+ />
+ <ComboboxContent anchor={triggerRef} side="bottom" sideOffset={6} className="min-w-[280px]">
+ <ComboboxInput placeholder="Search tables..." />
+ <ComboboxEmpty>No tables found.</ComboboxEmpty>
+ <ComboboxList>
+ {(group: TableOptionGroup) => (
+ <ComboboxGroup key={group.value} items={group.items}>
+ <ComboboxLabel>{group.value}</ComboboxLabel>
+ <ComboboxCollection>
+ {(tableName: string) => (
+ <ComboboxItem key={tableName} value={tableName}>
+ {tableName}
+ </ComboboxItem>
+ )}
+ </ComboboxCollection>
+ </ComboboxGroup>
+ )}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )
+}
diff --git a/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx b/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx
index 536e9b3802c5..abe8bbf66291 100644
--- a/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx
+++ b/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx
@@ -1,28 +1,27 @@
import { useActions, useValues } from 'kea'
import { Field, Form } from 'kea-forms'
-import { useState } from 'react'
-import { IconCheckCircle, IconCollapse, IconExpand } from '@posthog/icons'
+import { IconCheckCircle } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
LemonButtonProps,
- LemonCard,
LemonDivider,
LemonInput,
LemonModal,
LemonSearchableSelect,
- LemonSelect,
+ LemonTable,
LemonTag,
Spinner,
} from '@posthog/lemon-ui'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { HogQLDropdown } from 'lib/components/HogQLDropdown/HogQLDropdown'
-import { TablePreview } from 'lib/components/TablePreview/TablePreview'
-import { IconLink, IconSwapHoriz } from 'lib/lemon-ui/icons'
+import { IconLink } from 'lib/lemon-ui/icons'
+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { viewLinkLogic } from 'scenes/data-warehouse/viewLinkLogic'
+import { TableCombobox } from 'scenes/data-warehouse/TableCombobox'
+import { JoinKeyMode, KeySelectOption, viewLinkLogic } from 'scenes/data-warehouse/viewLinkLogic'
import { DatabaseSchemaField } from '~/queries/schema/schema-general'
@@ -41,7 +40,7 @@ interface ModeConfig {
lockJoiningTable: boolean
lockJoiningKey: boolean
sourceSqlPlaceholder: string
- showAdvancedSettings: boolean
+ showAccessorField: boolean
}
const DEFAULT_MODE_CONFIG: ModeConfig = {
@@ -54,7 +53,7 @@ const DEFAULT_MODE_CONFIG: ModeConfig = {
lockJoiningTable: false,
lockJoiningKey: false,
sourceSqlPlaceholder: HOGQL_EDITOR_PLACEHOLDER,
- showAdvancedSettings: true,
+ showAccessorField: true,
}
const MODE_CONFIGS: Record<Mode, ModeConfig> = {
@@ -71,7 +70,7 @@ const MODE_CONFIGS: Record<Mode, ModeConfig> = {
lockJoiningTable: true,
lockJoiningKey: true,
sourceSqlPlaceholder: HOGQL_EDITOR_PLACEHOLDER_REVENUE_ANALYTICS,
- showAdvancedSettings: false,
+ showAccessorField: false,
},
}
@@ -86,7 +85,7 @@ export function ViewLinkModal({ mode }: ViewLinkModalProps): JSX.Element {
description={config.description}
isOpen={isJoinTableModalOpen}
onClose={toggleJoinTableModal}
- width={1200}
+ width={900}
>
<ViewLinkForm config={config} />
</LemonModal>
@@ -95,7 +94,7 @@ export function ViewLinkModal({ mode }: ViewLinkModalProps): JSX.Element {
export function ViewLinkForm({ config = DEFAULT_MODE_CONFIG }: { config?: ModeConfig }): JSX.Element {
const {
- tableOptions,
+ groupedTableOptions,
selectedJoiningTableName,
selectedSourceTableName,
sourceTableKeys,
@@ -104,17 +103,10 @@ export function ViewLinkForm({ config = DEFAULT_MODE_CONFIG }: { config?: ModeCo
error,
fieldName,
isNewJoin,
- selectedSourceKey,
selectedJoiningKey,
- sourceIsUsingHogQLExpression,
- joiningIsUsingHogQLExpression,
+ sourceKeyMode,
+ joiningKeyMode,
isViewLinkSubmitting,
- selectedSourceTable,
- selectedJoiningTable,
- sourceTablePreviewData,
- joiningTablePreviewData,
- sourceTablePreviewLoading,
- joiningTablePreviewLoading,
saveDisabledReason,
} = useValues(viewLinkLogic)
const {
@@ -124,219 +116,114 @@ export function ViewLinkForm({ config = DEFAULT_MODE_CONFIG }: { config?: ModeCo
setFieldName,
selectSourceKey,
selectJoiningKey,
+ setSourceKeyMode,
+ setJoiningKeyMode,
} = useActions(viewLinkLogic)
- const [advancedSettingsExpanded, setAdvancedSettingsExpanded] = useState(false)
return (
<Form logic={viewLinkLogic} formKey="viewLink" enableFormOnSubmit>
- <div className="flex flex-row items-start justify-between gap-4">
- <LemonCard className="flex-1 p-0 max-w-136">
- <div className="flex flex-col gap-4 p-4">
- <div title="source-table-name-and-key" className="flex flex-row gap-4">
- <div title="source-table-name" className="flex-1">
- <span className="l4">Source table</span>
- <div className="text-wrap break-all mt-2">
- {config.lockSourceTable || !isNewJoin ? (
- <div>{selectedSourceTableName ?? ''}</div>
- ) : (
- <Field name="source_table_name">
- <LemonSearchableSelect
- fullWidth
- options={tableOptions}
- onSelect={selectSourceTable}
- placeholder="Select a table"
- />
- </Field>
- )}
- </div>
- </div>
- <div title="source-table-key" className="flex-1">
- <span className="l4">Source table key</span>
- <div className="text-wrap break-all mt-2">
- <Field name="source_table_key">
- {({ value, onChange }) => (
- <div className="flex flex-col gap-2">
- <LemonSelect
- fullWidth
- onSelect={selectSourceKey}
- onChange={onChange}
- value={sourceIsUsingHogQLExpression ? '' : (value ?? undefined)}
- disabledReason={
- selectedSourceTableName
- ? ''
- : 'Select a table to choose a join key'
- }
- options={[
- ...sourceTableKeys,
- { value: '', label: <span>SQL expression</span> },
- ]}
- placeholder="Select a key"
- />
- {sourceIsUsingHogQLExpression && (
- <div className="flex-1">
- <HogQLDropdown
- hogQLValue={value ?? ''}
- onHogQLValueChange={onChange}
- tableName={selectedSourceTableName ?? ''}
- hogQLEditorPlaceholder={config.sourceSqlPlaceholder}
- />
- </div>
- )}
- </div>
- )}
- </Field>
- </div>
- </div>
- </div>
- </div>
- <div className="pt-2">
- {selectedSourceTable && (
- <TablePreview
- table={selectedSourceTable}
- emptyMessage="Select a source table to view preview"
- previewData={sourceTablePreviewData}
- loading={sourceTablePreviewLoading}
- selectedKey={selectedSourceKey}
- />
- )}
- </div>
- </LemonCard>
-
- <div className="flex items-center mt-16">
- <IconSwapHoriz />
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium">Join</span>
+ {config.lockSourceTable || !isNewJoin ? (
+ <span className="font-mono font-medium">{selectedSourceTableName ?? ''}</span>
+ ) : (
+ <Field name="source_table_name">
+ {({ onChange }) => (
+ <TableCombobox
+ groups={groupedTableOptions}
+ value={selectedSourceTableName}
+ onChange={(tableName) => {
+ onChange(tableName)
+ selectSourceTable(tableName)
+ }}
+ aria-label="Source table"
+ />
+ )}
+ </Field>
+ )}
+ <span className="font-medium">to</span>
+ {config.lockJoiningTable ? (
+ <span className="font-mono font-medium">{selectedJoiningTableName ?? ''}</span>
+ ) : (
+ <Field name="joining_table_name">
+ {({ onChange }) => (
+ <TableCombobox
+ groups={groupedTableOptions}
+ value={selectedJoiningTableName}
+ onChange={(tableName) => {
+ onChange(tableName)
+ selectJoiningTable(tableName)
+ }}
+ aria-label="Joining table"
+ />
+ )}
+ </Field>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium">where</span>
+ <JoinKeyControl
+ formFieldName="source_table_key"
+ mode={sourceKeyMode}
+ onModeChange={setSourceKeyMode}
+ columnOptions={sourceTableKeys}
+ onSelectColumn={selectSourceKey}
+ tableName={selectedSourceTableName}
+ sqlPlaceholder={config.sourceSqlPlaceholder}
+ />
+ <span className="font-medium">=</span>
+ {config.lockJoiningKey ? (
+ <span className="font-mono font-medium">{selectedJoiningKey ?? ''}</span>
+ ) : (
+ <JoinKeyControl
+ formFieldName="joining_table_key"
+ mode={joiningKeyMode}
+ onModeChange={setJoiningKeyMode}
+ columnOptions={joiningTableKeys}
+ onSelectColumn={selectJoiningKey}
+ tableName={selectedJoiningTableName}
+ sqlPlaceholder={HOGQL_EDITOR_PLACEHOLDER}
+ />
+ )}
</div>
-
- <LemonCard className="flex-1 p-0 max-w-136">
- <div className="flex flex-col gap-4 p-4">
- <div title="joining-table-name-and-key" className="flex flex-row gap-4">
- <div title="joining-table-name" className="flex-1">
- <span className="l4">Joining table</span>
- <div className="text-wrap break-all mt-2">
- {config.lockJoiningTable ? (
- <div>{selectedJoiningTableName ?? ''}</div>
- ) : (
- <Field name="joining_table_name">
- <LemonSearchableSelect
- fullWidth
- options={tableOptions}
- onSelect={selectJoiningTable}
- placeholder="Select a table"
- />
- </Field>
- )}
- </div>
- </div>
- <div title="joining-table-key" className="flex-1">
- <span className="l4">Joining table key</span>
- <div className="text-wrap break-all mt-2">
- {config.lockJoiningKey ? (
- <div className="h-10 flex items-center px-3 py-2">
- {selectedJoiningKey ?? ''}
- </div>
- ) : (
- <Field name="joining_table_key">
- {({ value, onChange }) => (
- <div className="flex flex-col gap-2">
- <LemonSelect
- fullWidth
- onSelect={selectJoiningKey}
- onChange={onChange}
- value={
- joiningIsUsingHogQLExpression ? '' : (value ?? undefined)
- }
- disabledReason={
- selectedJoiningTableName
- ? ''
- : 'Select a table to choose a join key'
- }
- options={[
- ...joiningTableKeys,
- { value: '', label: <span>SQL expression</span> },
- ]}
- placeholder="Select a key"
- />
- {joiningIsUsingHogQLExpression && (
- <div className="flex-1">
- <HogQLDropdown
- hogQLValue={value ?? ''}
- onHogQLValueChange={onChange}
- tableName={selectedJoiningTableName ?? ''}
- hogQLEditorPlaceholder={HOGQL_EDITOR_PLACEHOLDER}
- />
- </div>
- )}
- </div>
- )}
- </Field>
- )}
- </div>
- </div>
- </div>
- </div>
- <div className="space-y-4 pt-2">
- {selectedJoiningTable && (
- <TablePreview
- table={selectedJoiningTable}
- emptyMessage="Select a joining table to view preview"
- previewData={joiningTablePreviewData}
- loading={joiningTablePreviewLoading}
- selectedKey={selectedJoiningKey}
- />
- )}
- </div>
- </LemonCard>
</div>
- <div className="w-full mt-4">
- {config.showAdvancedSettings && sqlCodeSnippet && (
- <div className="w-full mt-2">
- <LemonDivider className="mt-4 mb-4" />
- <LemonButton
- fullWidth
- onClick={() => setAdvancedSettingsExpanded(!advancedSettingsExpanded)}
- sideIcon={advancedSettingsExpanded ? <IconCollapse /> : <IconExpand />}
- >
- <div>
- <h3 className="l4 mt-2">Advanced settings</h3>
- <div className="text-secondary mb-2 font-medium">
- Customize how the fields are accessed
- </div>
- </div>
- </LemonButton>
- </div>
- )}
- {config.showAdvancedSettings && sqlCodeSnippet && advancedSettingsExpanded && (
- <>
- <div className="mt-3 flex flex-row justify-between items-center w-full">
- <div className="w-full">
- <span className="l4">Field name</span>
- <Field
- name="field_name"
- hint={`Pick a field name to access ${selectedJoiningTableName} from ${selectedSourceTableName}`}
- >
- <LemonInput
- value={fieldName}
- onChange={(fieldName) => setFieldName(fieldName)}
- placeholder="Field name"
- />
- </Field>
- </div>
+ <JoinValidationStatus />
+ {config.showAccessorField && sqlCodeSnippet && (
+ <>
+ <LemonDivider className="mt-4 mb-4" />
+ <div className="flex flex-col gap-3 w-full">
+ <div>
+ <span className="l4">Field name</span>
+ <Field name="field_name">
+ <LemonInput
+ size="small"
+ className="max-w-64"
+ value={fieldName}
+ onChange={(fieldName) => setFieldName(fieldName)}
+ placeholder="Field name"
+ />
+ </Field>
</div>
- <div className="mt-4 flex w-full">
- <CodeSnippet className="w-full" language={Language.SQL}>
+ <div>
+ <span className="l4">Query it like this</span>
+ <CodeSnippet className="w-full mt-2" language={Language.SQL}>
{sqlCodeSnippet}
</CodeSnippet>
- </div>
- </>
- )}
- {error && (
- <div className="flex w-full">
- <div className="text-danger flex text-sm overflow-auto">
- <span>{error}</span>
+ <div className="text-muted text-xs mt-1">
+ {`How you'll reach ${selectedJoiningTableName} from ${selectedSourceTableName}`}
+ </div>
</div>
</div>
- )}
- </div>
- <JoinValidationStatus />
+ </>
+ )}
+ {error && (
+ <div className="flex w-full mt-2">
+ <div className="text-danger flex text-sm overflow-auto">
+ <span>{error}</span>
+ </div>
+ </div>
+ )}
<LemonDivider className="mt-4 mb-4" />
<div className="flex flex-row gap-2 justify-end w-full">
<LemonButton type="secondary" onClick={toggleJoinTableModal}>
@@ -355,6 +242,107 @@ export function ViewLinkForm({ config = DEFAULT_MODE_CONFIG }: { config?: ModeCo
)
}
+const KEY_MODE_OPTIONS: { value: JoinKeyMode; label: string }[] = [
+ { value: 'column', label: 'Column' },
+ { value: 'sql_expression', label: 'SQL' },
+]
+
+interface JoinKeyControlProps {
+ formFieldName: 'source_table_key' | 'joining_table_key'
+ mode: JoinKeyMode
+ onModeChange: (mode: JoinKeyMode) => void
+ columnOptions: KeySelectOption[]
+ onSelectColumn: (key: string) => void
+ tableName: string | null
+ sqlPlaceholder: string
+}
+
+function JoinKeyControl({
+ formFieldName,
+ mode,
+ onModeChange,
+ columnOptions,
+ onSelectColumn,
+ tableName,
+ sqlPlaceholder,
+}: JoinKeyControlProps): JSX.Element {
+ return (
+ <div className="flex items-center gap-1">
+ <Field name={formFieldName}>
+ {({ value, onChange }) =>
+ mode === 'column' ? (
+ <LemonSearchableSelect
+ size="small"
+ onSelect={onSelectColumn}
+ onChange={onChange}
+ value={value ?? undefined}
+ disabledReason={tableName ? '' : 'Select a table first'}
+ options={columnOptions}
+ placeholder="Select a key"
+ searchPlaceholder="Search columns..."
+ // Labels are JSX (name + type tag); the searchable text is the value.
+ searchKeys={['value']}
+ className="min-w-40"
+ />
+ ) : (
+ <HogQLDropdown
+ size="small"
+ hogQLValue={value ?? ''}
+ onHogQLValueChange={onChange}
+ tableName={tableName ?? ''}
+ hogQLEditorPlaceholder={sqlPlaceholder}
+ />
+ )
+ }
+ </Field>
+ <LemonSegmentedButton
+ size="small"
+ value={mode}
+ onChange={onModeChange}
+ options={KEY_MODE_OPTIONS}
+ disabledReason={tableName ? undefined : 'Select a table first'}
+ />
+ </div>
+ )
+}
+
+function JoinMatchPreview(): JSX.Element | null {
+ const { joinValidation } = useValues(viewLinkLogic)
+ const response = joinValidation.response
+
+ if (joinValidation.status !== 'valid' || !response) {
+ return null
+ }
+
+ const COLUMN_TITLES: Record<string, string> = {
+ source_key: 'Source key',
+ joining_key: 'Joining key',
+ }
+ const columns = (response.columns ?? []).map((column, index) => ({
+ title: COLUMN_TITLES[column] ?? column,
+ key: column,
+ render: (_: any, row: any[]) => <span className="font-mono text-xs">{String(row[index] ?? '')}</span>,
+ }))
+
+ return (
+ <div className="flex flex-col gap-2">
+ {response.match_rate != null && response.total_rows != null && (
+ <span className="text-secondary text-sm">
+ {`${Math.round(response.match_rate * 100)}% of ${response.total_rows.toLocaleString()} sampled rows matched`}
+ </span>
+ )}
+ {columns.length > 0 && response.results.length > 0 && (
+ <LemonTable
+ size="small"
+ dataSource={response.results}
+ columns={columns}
+ rowKey={(_, index) => String(index)}
+ />
+ )}
+ </div>
+ )
+}
+
function JoinValidationStatus(): JSX.Element | null {
const { joinValidation, keyTypeMismatchWarning } = useValues(viewLinkLogic)
@@ -368,10 +356,13 @@ function JoinValidationStatus(): JSX.Element | null {
</div>
)}
{joinValidation.status === 'valid' && (
- <div className="flex items-center gap-2 text-success">
- <IconCheckCircle />
- <span>Join is valid</span>
- </div>
+ <>
+ <div className="flex items-center gap-2 text-success">
+ <IconCheckCircle />
+ <span>Join is valid</span>
+ </div>
+ <JoinMatchPreview />
+ </>
)}
{joinValidation.status === 'valid' && joinValidation.msg && (
<LemonBanner type="warning">{joinValidation.msg}</LemonBanner>
diff --git a/frontend/src/scenes/data-warehouse/viewLinkLogic.test.tsx b/frontend/src/scenes/data-warehouse/viewLinkLogic.test.tsx
index 2ec5f1170042..60178ad6076b 100644
--- a/frontend/src/scenes/data-warehouse/viewLinkLogic.test.tsx
+++ b/frontend/src/scenes/data-warehouse/viewLinkLogic.test.tsx
@@ -1,6 +1,9 @@
import { expectLogic } from 'kea-test-utils'
+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+
import { useMocks } from '~/mocks/jest'
+import { DatabaseSchemaTable } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { viewLinkLogic } from './viewLinkLogic'
@@ -74,6 +77,67 @@ describe('viewLinkLogic', () => {
expect(logic.values.joinValidation.msg).toBe('Validation query returned no results')
})
+ it('buckets tables into picker groups and keeps unknown types reachable', async () => {
+ const table = (name: string, type: string): DatabaseSchemaTable =>
+ ({ name, type, fields: {}, id: name }) as unknown as DatabaseSchemaTable
+ databaseTableListLogic.findMounted()?.actions.loadDatabaseSuccess({
+ tables: {
+ events: table('events', 'posthog'),
+ stripe_customers: table('stripe_customers', 'data_warehouse'),
+ my_view: table('my_view', 'view'),
+ odd_one: table('odd_one', 'something_new'),
+ },
+ } as any)
+
+ expect(logic.values.groupedTableOptions).toEqual([
+ { value: 'PostHog tables', items: ['events'] },
+ { value: 'Data warehouse', items: ['stripe_customers'] },
+ { value: 'Views', items: ['my_view'] },
+ { value: 'Other', items: ['odd_one'] },
+ ])
+ })
+
+ it('keeps an explicit SQL expression mode even though the field is still empty', async () => {
+ logic.actions.selectJoiningTable('persons')
+ logic.actions.setJoiningKeyMode('sql_expression')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.joiningKeyMode).toBe('sql_expression')
+ })
+
+ it('drops the explicit key mode when the table changes', async () => {
+ logic.actions.setJoiningKeyMode('sql_expression')
+ logic.actions.selectJoiningTable('persons')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.joiningKeyModeOverride).toBeNull()
+ })
+
+ it('clears the key when its table changes', async () => {
+ logic.actions.selectSourceTable('events')
+ logic.actions.setViewLinkValue('source_table_key', 'uuid')
+ logic.actions.selectSourceTable('persons')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.viewLink.source_table_key).toBeNull()
+ expect(logic.values.selectedSourceKey).toBeNull()
+ })
+
+ it('keeps a field name the user typed when the joining table changes', async () => {
+ logic.actions.setFieldName('my_accessor')
+ logic.actions.selectJoiningTable('persons')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.fieldName).toBe('my_accessor')
+ })
+
+ it('autofills the field name from the joining table while untouched', async () => {
+ logic.actions.selectJoiningTable('postgres.public.customers')
+ await expectLogic(logic).toDispatchActions(['autofillFieldName'])
+
+ expect(logic.values.fieldName).toBe('postgres_public_customers')
+ })
+
it('resets validation state when the modal closes', async () => {
logic.actions.toggleJoinTableModal()
fillJoin()
diff --git a/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx b/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
index a11325493ecb..1ff52f591d7b 100644
--- a/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
@@ -8,9 +8,7 @@ import api from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
-import { performQuery } from '~/queries/query'
-import { DatabaseSchemaField, HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
-import { hogql } from '~/queries/utils'
+import { DatabaseSchemaField } from '~/queries/schema/schema-general'
import { DataWarehouseViewLink, DataWarehouseViewLinkValidation } from '~/types'
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
@@ -45,6 +43,20 @@ export interface KeySelectOption {
disabledReason?: string
}
+export type JoinKeyMode = 'column' | 'sql_expression'
+
+/** Shape Base UI's Combobox expects for grouped items: a label plus the group's own items. */
+export interface TableOptionGroup {
+ value: string
+ items: string[]
+}
+
+const TABLE_GROUPS: { label: string; types: DatabaseSchemaTable['type'][] }[] = [
+ { label: 'PostHog tables', types: ['posthog', 'system'] },
+ { label: 'Data warehouse', types: ['data_warehouse', 'batch_export'] },
+ { label: 'Views', types: ['view', 'materialized_view', 'managed_view', 'endpoint'] },
+]
+
const disabledReasonForColumn = (column: DatabaseSchemaField): string | undefined => {
if (column.type === 'lazy_table') {
return "Lazy tables can't be joined directly, use SQL expression to join with lazy table fields"
@@ -62,6 +74,8 @@ export interface viewLinkLogicValues {
allTables: DatabaseSchemaTable[] // databaseTableListLogic
error: string | null
fieldName: string
+ fieldNameTouched: boolean
+ groupedTableOptions: TableOptionGroup[]
isJoinTableModalOpen: boolean
isNewJoin: boolean
isViewLinkSubmitting: boolean
@@ -69,9 +83,9 @@ export interface viewLinkLogicValues {
joinToEdit: DataWarehouseViewLink | null
joinValidation: JoinValidationState
joiningIsUsingHogQLExpression: boolean
+ joiningKeyMode: JoinKeyMode
+ joiningKeyModeOverride: JoinKeyMode | null
joiningTableKeys: KeySelectOption[]
- joiningTablePreviewData: Record<string, any>[]
- joiningTablePreviewLoading: boolean
keyTypeMismatchWarning: string | null
saveDisabledReason: string | null
selectedJoiningKey: string | null
@@ -82,9 +96,9 @@ export interface viewLinkLogicValues {
selectedSourceTableName: string | null
showViewLinkErrors: boolean
sourceIsUsingHogQLExpression: boolean
+ sourceKeyMode: JoinKeyMode
+ sourceKeyModeOverride: JoinKeyMode | null
sourceTableKeys: KeySelectOption[]
- sourceTablePreviewData: Record<string, any>[]
- sourceTablePreviewLoading: boolean
sqlCodeSnippet: string | null
tableOptions: {
label: string
@@ -113,6 +127,9 @@ export interface viewLinkLogicActions {
force?: boolean
} // databaseTableListLogic
loadJoins: () => any // joinsLogic
+ autofillFieldName: (fieldName: string) => {
+ fieldName: string
+ }
checkKeyTypeMismatch: () => void
clearModalFields: () => {
value: true
@@ -124,12 +141,6 @@ export interface viewLinkLogicActions {
column: any
table: any
}
- loadJoiningTablePreview: (tableName: string) => {
- tableName: string
- }
- loadSourceTablePreview: (tableName: string) => {
- tableName: string
- }
resetJoinValidation: () => {
value: true
}
@@ -159,14 +170,14 @@ export interface viewLinkLogicActions {
setFieldName: (fieldName: string) => {
fieldName: string
}
- setJoiningTablePreviewData: (data: Record<string, any>[]) => {
- data: Record<string, any>[]
+ setJoiningKeyMode: (mode: JoinKeyMode) => {
+ mode: JoinKeyMode
}
setKeyTypeMismatchWarning: (warning: string | null) => {
warning: string | null
}
- setSourceTablePreviewData: (data: Record<string, any>[]) => {
- data: Record<string, any>[]
+ setSourceKeyMode: (mode: JoinKeyMode) => {
+ mode: JoinKeyMode
}
setViewLinkManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
@@ -248,6 +259,7 @@ export interface viewLinkLogicMeta {
label: string
value: string
}[]
+ groupedTableOptions: (allTables: DatabaseSchemaTable[]) => TableOptionGroup[]
sourceTableKeys: (selectedSourceTable: DatabaseSchemaTable | undefined) => KeySelectOption[]
joiningTableKeys: (selectedJoiningTable: DatabaseSchemaTable | undefined) => KeySelectOption[]
sqlCodeSnippet: (
@@ -255,6 +267,11 @@ export interface viewLinkLogicMeta {
selectedJoiningTableName: string | null,
fieldName: string
) => string | null
+ sourceKeyMode: (sourceKeyModeOverride: JoinKeyMode | null, sourceIsUsingHogQLExpression: boolean) => JoinKeyMode
+ joiningKeyMode: (
+ joiningKeyModeOverride: JoinKeyMode | null,
+ joiningIsUsingHogQLExpression: boolean
+ ) => JoinKeyMode
saveDisabledReason: (joinValidation: JoinValidationState) => string | null
}
}
@@ -285,11 +302,10 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
setError: (error: string) => ({ error }),
setFieldName: (fieldName: string) => ({ fieldName }),
clearModalFields: true,
- loadSourceTablePreview: (tableName: string) => ({ tableName }),
- loadJoiningTablePreview: (tableName: string) => ({ tableName }),
- setSourceTablePreviewData: (data: Record<string, any>[]) => ({ data }),
- setJoiningTablePreviewData: (data: Record<string, any>[]) => ({ data }),
setKeyTypeMismatchWarning: (warning: string | null) => ({ warning }),
+ setSourceKeyMode: (mode: JoinKeyMode) => ({ mode }),
+ setJoiningKeyMode: (mode: JoinKeyMode) => ({ mode }),
+ autofillFieldName: (fieldName: string) => ({ fieldName }),
validateJoin: () => {},
validateJoinStarted: true,
validateJoinSuccess: (response: DataWarehouseViewLinkValidation) => ({ response }),
@@ -363,6 +379,12 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
null as string | null,
{
selectSourceKey: (_, { selectedKey }) => selectedKey,
+ // A key belongs to its table; keeping it across a table change would
+ // silently validate or save against a column of the wrong table.
+ selectSourceTable: () => null,
+ // A column and a SQL expression aren't interchangeable, so drop the key when the
+ // mode switches rather than reinterpreting the old value under the new mode.
+ setSourceKeyMode: () => null,
toggleNewJoinModal: (_, { join }) => join?.source_table_key ?? null,
toggleEditJoinModal: (_, { join }) => join.source_table_key ?? null,
clearModalFields: () => null,
@@ -372,6 +394,8 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
null as string | null,
{
selectJoiningKey: (_, { selectedKey }) => selectedKey,
+ selectJoiningTable: () => null,
+ setJoiningKeyMode: () => null,
toggleNewJoinModal: (_, { join }) => join?.joining_table_key ?? null,
toggleEditJoinModal: (_, { join }) => join.joining_table_key ?? null,
clearModalFields: () => null,
@@ -381,12 +405,23 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
'' as string,
{
setFieldName: (_, { fieldName }) => fieldName,
- selectJoiningTable: (_, { selectedTableName }) => selectedTableName.replaceAll('.', '_'),
+ autofillFieldName: (_, { fieldName }) => fieldName,
toggleNewJoinModal: (_, { join }) => join?.field_name ?? '',
toggleEditJoinModal: (_, { join }) => join.field_name ?? '',
clearModalFields: () => '',
},
],
+ fieldNameTouched: [
+ false as boolean,
+ {
+ setFieldName: () => true,
+ toggleNewJoinModal: () => false,
+ // An existing join's accessor is user-owned; treat it as touched so changing the
+ // joining table doesn't autofill over a custom accessor and break queries using it.
+ toggleEditJoinModal: (_, { join }) => !!join.field_name,
+ clearModalFields: () => false,
+ },
+ ],
isJoinTableModalOpen: [
false,
{
@@ -402,6 +437,25 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
clearModalFields: () => null,
},
],
+ // Only an explicit toggle is stored. The mode is otherwise derived from the key, so it
+ // stays correct when the schema arrives after the modal opens; picking "SQL expression"
+ // empties the field, which is why derivation alone would bounce the user back.
+ sourceKeyModeOverride: [
+ null as JoinKeyMode | null,
+ {
+ setSourceKeyMode: (_, { mode }) => mode,
+ selectSourceTable: () => null,
+ clearModalFields: () => null,
+ },
+ ],
+ joiningKeyModeOverride: [
+ null as JoinKeyMode | null,
+ {
+ setJoiningKeyMode: (_, { mode }) => mode,
+ selectJoiningTable: () => null,
+ clearModalFields: () => null,
+ },
+ ],
keyTypeMismatchWarning: [
null as null | string,
{
@@ -411,34 +465,8 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
selectSourceTable: () => null,
selectJoiningKey: () => null,
selectJoiningTable: () => null,
- },
- ],
- sourceTablePreviewData: [
- [] as Record<string, any>[],
- {
- setSourceTablePreviewData: (_, { data }) => data,
- clearModalFields: () => [],
- },
- ],
- joiningTablePreviewData: [
- [] as Record<string, any>[],
- {
- setJoiningTablePreviewData: (_, { data }) => data,
- clearModalFields: () => [],
- },
- ],
- sourceTablePreviewLoading: [
- false as boolean,
- {
- loadSourceTablePreview: () => true,
- setSourceTablePreviewData: () => false,
- },
- ],
- joiningTablePreviewLoading: [
- false as boolean,
- {
- loadJoiningTablePreview: () => true,
- setJoiningTablePreviewData: () => false,
+ setSourceKeyMode: () => null,
+ setJoiningKeyMode: () => null,
},
],
}),
@@ -502,22 +530,10 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
listeners(({ actions, values }) => ({
toggleNewJoinModal: ({ join }) => {
actions.setViewLinkValues(join ?? NEW_VIEW_LINK)
- if (join?.source_table_name) {
- actions.loadSourceTablePreview(join.source_table_name)
- }
- if (join?.joining_table_name) {
- actions.loadJoiningTablePreview(join.joining_table_name)
- }
actions.validateJoin()
},
toggleEditJoinModal: ({ join }) => {
actions.setViewLinkValues(join)
- if (join.source_table_name) {
- actions.loadSourceTablePreview(join.source_table_name)
- }
- if (join.joining_table_name) {
- actions.loadJoiningTablePreview(join.joining_table_name)
- }
actions.validateJoin()
},
setViewLinkValue: ({ name }) => {
@@ -527,18 +543,25 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
actions.validateJoin()
}
},
- selectSourceTable: async ({ selectedTableName }) => {
- if (selectedTableName) {
- actions.loadSourceTablePreview(selectedTableName)
- }
+ selectSourceTable: async () => {
+ actions.setViewLinkValue('source_table_key', null)
actions.validateJoin()
},
selectJoiningTable: async ({ selectedTableName }) => {
- if (selectedTableName) {
- actions.loadJoiningTablePreview(selectedTableName)
+ actions.setViewLinkValue('joining_table_key', null)
+ if (selectedTableName && !values.fieldNameTouched) {
+ actions.autofillFieldName(selectedTableName.replaceAll('.', '_'))
}
actions.validateJoin()
},
+ // Clear the form value on a mode switch so a column and a SQL expression can't be
+ // reinterpreted under the other mode when validating or saving.
+ setSourceKeyMode: () => {
+ actions.setViewLinkValue('source_table_key', null)
+ },
+ setJoiningKeyMode: () => {
+ actions.setViewLinkValue('joining_table_key', null)
+ },
checkKeyTypeMismatch: () => {
if (values.selectedSourceKey && values.selectedJoiningKey) {
const sourceColumn = Object.values(values.selectedSourceTable?.fields ?? {}).find(
@@ -564,12 +587,6 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
actions.checkKeyTypeMismatch()
actions.validateJoin()
},
- loadSourceTablePreview: async ({ tableName }) => {
- await loadTablePreviewData(tableName, actions.setSourceTablePreviewData)
- },
- loadJoiningTablePreview: async ({ tableName }) => {
- await loadTablePreviewData(tableName, actions.setJoiningTablePreviewData)
- },
validateJoin: async (_, breakpoint) => {
await breakpoint(VALIDATE_JOIN_DEBOUNCE_MS)
@@ -658,6 +675,20 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
label: table.name,
})),
],
+ groupedTableOptions: [
+ (s) => [s.allTables],
+ (tables: import('~/queries/schema/schema-general').DatabaseSchemaTable[]): TableOptionGroup[] => {
+ const groups = TABLE_GROUPS.map(({ label, types }) => ({
+ value: label,
+ items: tables.filter((table) => types.includes(table.type)).map((table) => table.name),
+ }))
+ // A table type missing from TABLE_GROUPS would otherwise silently disappear
+ // from the picker.
+ const grouped = new Set(groups.flatMap((group) => group.items))
+ const ungrouped = tables.map((table) => table.name).filter((name) => !grouped.has(name))
+ return [...groups, { value: 'Other', items: ungrouped }].filter((group) => group.items.length > 0)
+ },
+ ],
sourceTableKeys: [
(s) => [s.selectedSourceTable],
(
@@ -703,6 +734,16 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
return `SELECT ${tableAlias}.${fieldName || ''} FROM ${selectedSourceTableName} ${tableAlias}`
},
],
+ sourceKeyMode: [
+ (s) => [s.sourceKeyModeOverride, s.sourceIsUsingHogQLExpression],
+ (override: JoinKeyMode | null, isExpression: boolean): JoinKeyMode =>
+ override ?? (isExpression ? 'sql_expression' : 'column'),
+ ],
+ joiningKeyMode: [
+ (s) => [s.joiningKeyModeOverride, s.joiningIsUsingHogQLExpression],
+ (override: JoinKeyMode | null, isExpression: boolean): JoinKeyMode =>
+ override ?? (isExpression ? 'sql_expression' : 'column'),
+ ],
saveDisabledReason: [
(s) => [s.joinValidation],
(joinValidation: JoinValidationState): string | null =>
@@ -726,24 +767,3 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
},
})),
])
-
-async function loadTablePreviewData(
- tableName: string,
- setDataAction: (data: Record<string, any>[]) => void
-): Promise<void> {
- try {
- // An untagged HogQL query is rejected by the query-tag enforcement in sync_execute.
- const response = await performQuery<HogQLQuery>({
- kind: NodeKind.HogQLQuery,
- query: hogql`SELECT * FROM ${hogql.identifier(tableName)} LIMIT 10`,
- tags: { productKey: 'data_warehouse', name: 'view_link_table_preview' },
- })
- const transformedData = (response.results || []).map((row: any[]) =>
- Object.fromEntries((response.columns || []).map((column: string, index: number) => [column, row[index]]))
- )
- setDataAction(transformedData)
- } catch (error) {
- posthog.captureException(error)
- setDataAction([])
- }
-}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 9cb42a8166e7..c7d9a8cd5bd5 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6207,7 +6207,11 @@ export interface DataWarehouseViewLinkValidation {
is_valid: boolean
msg: string | null
hogql: string | null
+ columns: string[]
results: any[]
+ total_rows: number | null
+ matched_rows: number | null
+ match_rate: number | null
}
export interface QueryTabState {