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): consolidate join modal with auto-validation (#75555)

Thiago Salvatoreed30f8c74441
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e569750d796d..e79e39426b84 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6245,7 +6245,7 @@ snapshots:
scenes-app-inbox-scene--self-driving-paused--dark:
hash: v1.k794b7964.00929b96e59e35796acfc2f8d5f9f48e148c499b2932c227e1a4cf02c488bde0.0kZ4s9sfw8uPHzO2KT7GZ6vL6y-2qA4qzRoZW7n-bcU
scenes-app-inbox-scene--self-driving-paused--light:
- hash: v1.k794b7964.3801adf5236e9dcea0f1fa5eeffddd6826efb30725b70760369e486db3567e82.UPOnHRPFkJ4uMMemIpHngMRSjylkumiXVWPnADLiBF4
+ hash: v1.k794b7964.e2ed5feaafcc219cbecaedafed11618a60e0b39911f54121ae02acbf68270238.v1MEVslQu-332g2PB_trr6JIb-knUHeoA42roLiGQRI
scenes-app-inbox-tabs--pull-requests--dark:
hash: v1.k794b7964.dad4d6e7b9f1f68f8eaf4b31187c798dfab1631bb6bf20432ce9746f7df1de73.cqSvLKv0E6PFhnMnbn4FS6yIypKYMUKzoKniwrRI4WM
scenes-app-inbox-tabs--pull-requests--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 80d1fbfb45f1..984797ecfd1c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -293,7 +293,6 @@ export const FEATURE_FLAGS = {
DATA_WAREHOUSE_SEMANTIC_ENRICHMENT: 'data-warehouse-semantic-enrichment', // owner: #team-warehouse-sources
DEFAULT_EVALUATION_ENVIRONMENTS: 'default-evaluation-environments', // owner: @dmarticus #team-feature-flags
DROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analytics
- DWH_JOIN_TABLE_PREVIEW: 'dwh-join-table-preview', // owner: @arthurdedeus #team-customer-analytics
DWH_POSTGRES_CDC: 'dwh-postgres-cdc', // owner: #team-warehouse-sources
DWH_SOURCE_METRICS: 'dwh-source-metrics', // owner: #team-warehouse-sources
EDITOR_DRAFTS: 'editor-drafts', // owner: @EDsCODE #team-data-tools
diff --git a/frontend/src/scenes/data-warehouse/ViewLinkModal.scss b/frontend/src/scenes/data-warehouse/ViewLinkModal.scss
deleted file mode 100644
index 1273a6c05658..000000000000
--- a/frontend/src/scenes/data-warehouse/ViewLinkModal.scss
+++ /dev/null
@@ -1,3 +0,0 @@
-.form-error {
- color: var(--danger);
-}
diff --git a/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx b/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx
index 8825209375cf..536e9b3802c5 100644
--- a/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx
+++ b/frontend/src/scenes/data-warehouse/ViewLinkModal.tsx
@@ -1,10 +1,8 @@
-import './ViewLinkModal.scss'
-
import { useActions, useValues } from 'kea'
import { Field, Form } from 'kea-forms'
import { useState } from 'react'
-import { IconCollapse, IconExpand } from '@posthog/icons'
+import { IconCheckCircle, IconCollapse, IconExpand } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -16,12 +14,12 @@ import {
LemonSearchableSelect,
LemonSelect,
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 { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconLink, IconSwapHoriz } from 'lib/lemon-ui/icons'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { viewLinkLogic } from 'scenes/data-warehouse/viewLinkLogic'
@@ -33,46 +31,69 @@ export interface ViewLinkModalProps {
mode?: Mode
}
+const HOGQL_EDITOR_PLACEHOLDER = 'Enter SQL expression, such as:\n- pdi.distinct_id\n- properties.email'
+const HOGQL_EDITOR_PLACEHOLDER_REVENUE_ANALYTICS =
+ "Enter SQL expression, such as:\n- metadata.customer_id\n- metadata.organization_id\n- concat(email, ',', customer_id)"
+
+interface ModeConfig {
+ description: JSX.Element
+ lockSourceTable: boolean
+ lockJoiningTable: boolean
+ lockJoiningKey: boolean
+ sourceSqlPlaceholder: string
+ showAdvancedSettings: boolean
+}
+
+const DEFAULT_MODE_CONFIG: ModeConfig = {
+ description: (
+ <span>
+ Join two tables or views. Fields from the joined table become available in queries on the source table.
+ </span>
+ ),
+ lockSourceTable: false,
+ lockJoiningTable: false,
+ lockJoiningKey: false,
+ sourceSqlPlaceholder: HOGQL_EDITOR_PLACEHOLDER,
+ showAdvancedSettings: true,
+}
+
+const MODE_CONFIGS: Record<Mode, ModeConfig> = {
+ revenue_analytics: {
+ description: (
+ <span>
+ Join either the <code>persons</code> or <code>groups</code> table to the{' '}
+ <code>customer_revenue_view</code> Revenue analytics view. Fields from the joined view become available
+ in queries at the top level, including the <code>persons.$virt_revenue</code> and{' '}
+ <code>persons.$virt_mrr</code> virtual fields.
+ </span>
+ ),
+ lockSourceTable: true,
+ lockJoiningTable: true,
+ lockJoiningKey: true,
+ sourceSqlPlaceholder: HOGQL_EDITOR_PLACEHOLDER_REVENUE_ANALYTICS,
+ showAdvancedSettings: false,
+ },
+}
+
export function ViewLinkModal({ mode }: ViewLinkModalProps): JSX.Element {
const { isJoinTableModalOpen } = useValues(viewLinkLogic)
const { toggleJoinTableModal } = useActions(viewLinkLogic)
- const hasPreviewFlag = useFeatureFlag('DWH_JOIN_TABLE_PREVIEW')
+ const config = mode ? MODE_CONFIGS[mode] : DEFAULT_MODE_CONFIG
return (
<LemonModal
title="Join tables"
- description={
- mode === 'revenue_analytics' ? (
- <span>
- Define a join between either the <code>persons</code> or <code>groups</code> table and the{' '}
- <code>customer_revenue_view</code> Revenue analytics view. <br />
- <br />
- <b>All</b> fields from the joined table or view will be accessible in queries at the top level
- without needing to explicitly join the view. This will also enable you to see revenue for a
- person via the <code>persons.$virt_revenue</code> and <code>persons.$virt_mrr</code> virtual
- fields.
- </span>
- ) : (
- <span>
- Define a join between two tables or views. <b>All</b> fields from the joined table or view will
- be accessible in queries at the top level without needing to explicitly join the view.
- </span>
- )
- }
+ description={config.description}
isOpen={isJoinTableModalOpen}
onClose={toggleJoinTableModal}
- width={hasPreviewFlag ? 1200 : 700}
+ width={1200}
>
- {hasPreviewFlag ? <ViewLinkFormWithPreview mode={mode} /> : <ViewLinkForm mode={mode} />}
+ <ViewLinkForm config={config} />
</LemonModal>
)
}
-const HOGQL_EDITOR_PLACEHOLDER = 'Enter SQL expression, such as:\n- pdi.distinct_id\n- properties.email'
-const HOGQL_EDITOR_PLACEHOLDER_REVENUE_ANALYTICS =
- "Enter SQL expression, such as:\n- metadata.customer_id\n- metadata.organization_id\n- concat(email, ',', customer_id)"
-
-export function ViewLinkForm({ mode }: ViewLinkModalProps): JSX.Element {
+export function ViewLinkForm({ config = DEFAULT_MODE_CONFIG }: { config?: ModeConfig }): JSX.Element {
const {
tableOptions,
selectedJoiningTableName,
@@ -83,10 +104,18 @@ export function ViewLinkForm({ mode }: ViewLinkModalProps): JSX.Element {
error,
fieldName,
isNewJoin,
+ selectedSourceKey,
selectedJoiningKey,
sourceIsUsingHogQLExpression,
joiningIsUsingHogQLExpression,
isViewLinkSubmitting,
+ selectedSourceTable,
+ selectedJoiningTable,
+ sourceTablePreviewData,
+ joiningTablePreviewData,
+ sourceTablePreviewLoading,
+ joiningTablePreviewLoading,
+ saveDisabledReason,
} = useValues(viewLinkLogic)
const {
selectJoiningTable,
@@ -98,219 +127,6 @@ export function ViewLinkForm({ mode }: ViewLinkModalProps): JSX.Element {
} = useActions(viewLinkLogic)
const [advancedSettingsExpanded, setAdvancedSettingsExpanded] = useState(false)
- return (
- <Form logic={viewLinkLogic} formKey="viewLink" enableFormOnSubmit>
- <div className="flex flex-col w-full justify-between items-center">
- <div className="flex flex-row w-full justify-between">
- <div className="w-60">
- <span className="l4">Source Table</span>
- <div className="text-wrap break-all">
- {mode === 'revenue_analytics' || !isNewJoin ? (
- (selectedSourceTableName ?? '')
- ) : (
- <Field name="source_table_name">
- <LemonSelect
- fullWidth
- options={tableOptions}
- onSelect={selectSourceTable}
- placeholder="Select a table"
- />
- </Field>
- )}
- </div>
- </div>
- <div className="w-60">
- <span className="l4">Joining Table</span>
- <div className="text-wrap break-all">
- {mode === 'revenue_analytics' ? (
- (selectedJoiningTableName ?? '')
- ) : (
- <Field name="joining_table_name">
- <LemonSearchableSelect
- fullWidth
- options={tableOptions}
- onSelect={selectJoiningTable}
- placeholder="Select a table"
- />
- </Field>
- )}
- </div>
- </div>
- </div>
- <div className="mt-4 flex flex-row justify-between items-center w-full">
- <div className="w-60">
- <span className="l4">Source Table Key</span>
- <div className="text-wrap break-all">
- <Field name="source_table_key">
- {({ value, onChange }) => (
- <>
- <LemonSelect
- fullWidth
- onSelect={selectSourceKey}
- onChange={onChange}
- value={sourceIsUsingHogQLExpression ? '' : (value ?? undefined)}
- disabledReason={
- selectedSourceTableName ? '' : 'Select a table to choose join key'
- }
- options={[
- ...sourceTableKeys,
- { value: '', label: <span>SQL Expression</span> },
- ]}
- placeholder="Select a key"
- />
- {sourceIsUsingHogQLExpression && (
- <HogQLDropdown
- className="mt-2"
- hogQLValue={value}
- onHogQLValueChange={onChange}
- tableName={selectedSourceTableName ?? ''}
- hogQLEditorPlaceholder={
- mode === 'revenue_analytics'
- ? HOGQL_EDITOR_PLACEHOLDER_REVENUE_ANALYTICS
- : HOGQL_EDITOR_PLACEHOLDER
- }
- />
- )}
- </>
- )}
- </Field>
- </div>
- </div>
- <div className="mt-5">
- <IconSwapHoriz />
- </div>
- <div className="w-60">
- <span className="l4">Joining Table Key</span>
- <div className="text-wrap break-all">
- {mode === 'revenue_analytics' ? (
- (selectedJoiningKey ?? '')
- ) : (
- <Field name="joining_table_key">
- {({ value, onChange }) => (
- <>
- <LemonSelect
- fullWidth
- onSelect={selectJoiningKey}
- onChange={onChange}
- value={joiningIsUsingHogQLExpression ? '' : (value ?? undefined)}
- disabledReason={
- selectedJoiningTableName ? '' : 'Select a table to choose join key'
- }
- options={[
- ...joiningTableKeys,
- { value: '', label: <span>SQL Expression</span> },
- ]}
- placeholder="Select a key"
- />
- {joiningIsUsingHogQLExpression && (
- <HogQLDropdown
- className="mt-2"
- hogQLValue={value}
- onHogQLValueChange={onChange}
- tableName={selectedJoiningTableName ?? ''}
- hogQLEditorPlaceholder={HOGQL_EDITOR_PLACEHOLDER}
- />
- )}
- </>
- )}
- </Field>
- )}
- </div>
- </div>
- </div>
- {sqlCodeSnippet && mode !== 'revenue_analytics' && (
- <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>
- )}
- {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>
- </div>
- <div className="mt-4 flex w-full">
- <CodeSnippet className="w-full" 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>
- </div>
- )}
- </div>
- <LemonDivider className="mt-4 mb-4" />
- <div className="flex flex-row justify-end w-full">
- <LemonButton className="mr-3" type="secondary" onClick={toggleJoinTableModal}>
- Close
- </LemonButton>
- <LemonButton type="primary" htmlType="submit" loading={isViewLinkSubmitting}>
- Save
- </LemonButton>
- </div>
- </Form>
- )
-}
-
-export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Element {
- const {
- tableOptions,
- selectedJoiningTableName,
- selectedSourceTableName,
- sourceTableKeys,
- joiningTableKeys,
- sqlCodeSnippet,
- error,
- fieldName,
- isNewJoin,
- selectedSourceKey,
- selectedJoiningKey,
- sourceIsUsingHogQLExpression,
- joiningIsUsingHogQLExpression,
- isViewLinkSubmitting,
- selectedSourceTable,
- selectedJoiningTable,
- sourceTablePreviewData,
- joiningTablePreviewData,
- sourceTablePreviewLoading,
- joiningTablePreviewLoading,
- isJoinValidating,
- isJoinValid,
- validationError,
- validationWarning,
- } = useValues(viewLinkLogic)
- const { selectJoiningTable, selectSourceTable, setFieldName, selectSourceKey, selectJoiningKey, validateJoin } =
- 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">
@@ -318,13 +134,13 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
<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>
+ <span className="l4">Source table</span>
<div className="text-wrap break-all mt-2">
- {mode === 'revenue_analytics' || !isNewJoin ? (
+ {config.lockSourceTable || !isNewJoin ? (
<div>{selectedSourceTableName ?? ''}</div>
) : (
<Field name="source_table_name">
- <LemonSelect
+ <LemonSearchableSelect
fullWidth
options={tableOptions}
onSelect={selectSourceTable}
@@ -335,7 +151,7 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
</div>
</div>
<div title="source-table-key" className="flex-1">
- <span className="l4">Source Table Key</span>
+ <span className="l4">Source table key</span>
<div className="text-wrap break-all mt-2">
<Field name="source_table_key">
{({ value, onChange }) => (
@@ -348,11 +164,11 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
disabledReason={
selectedSourceTableName
? ''
- : 'Select a table to choose join key'
+ : 'Select a table to choose a join key'
}
options={[
...sourceTableKeys,
- { value: '', label: <span>SQL Expression</span> },
+ { value: '', label: <span>SQL expression</span> },
]}
placeholder="Select a key"
/>
@@ -362,11 +178,7 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
hogQLValue={value ?? ''}
onHogQLValueChange={onChange}
tableName={selectedSourceTableName ?? ''}
- hogQLEditorPlaceholder={
- mode === 'revenue_analytics'
- ? HOGQL_EDITOR_PLACEHOLDER_REVENUE_ANALYTICS
- : HOGQL_EDITOR_PLACEHOLDER
- }
+ hogQLEditorPlaceholder={config.sourceSqlPlaceholder}
/>
</div>
)}
@@ -398,9 +210,9 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
<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>
+ <span className="l4">Joining table</span>
<div className="text-wrap break-all mt-2">
- {mode === 'revenue_analytics' ? (
+ {config.lockJoiningTable ? (
<div>{selectedJoiningTableName ?? ''}</div>
) : (
<Field name="joining_table_name">
@@ -415,9 +227,9 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
</div>
</div>
<div title="joining-table-key" className="flex-1">
- <span className="l4">Joining Table Key</span>
+ <span className="l4">Joining table key</span>
<div className="text-wrap break-all mt-2">
- {mode === 'revenue_analytics' ? (
+ {config.lockJoiningKey ? (
<div className="h-10 flex items-center px-3 py-2">
{selectedJoiningKey ?? ''}
</div>
@@ -435,11 +247,11 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
disabledReason={
selectedJoiningTableName
? ''
- : 'Select a table to choose join key'
+ : 'Select a table to choose a join key'
}
options={[
...joiningTableKeys,
- { value: '', label: <span>SQL Expression</span> },
+ { value: '', label: <span>SQL expression</span> },
]}
placeholder="Select a key"
/>
@@ -475,7 +287,7 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
</LemonCard>
</div>
<div className="w-full mt-4">
- {sqlCodeSnippet && mode !== 'revenue_analytics' && (
+ {config.showAdvancedSettings && sqlCodeSnippet && (
<div className="w-full mt-2">
<LemonDivider className="mt-4 mb-4" />
<LemonButton
@@ -492,11 +304,11 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
</LemonButton>
</div>
)}
- {sqlCodeSnippet && advancedSettingsExpanded && (
+ {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>
+ <span className="l4">Field name</span>
<Field
name="field_name"
hint={`Pick a field name to access ${selectedJoiningTableName} from ${selectedSourceTableName}`}
@@ -524,58 +336,65 @@ export function ViewLinkFormWithPreview({ mode }: ViewLinkModalProps): JSX.Eleme
</div>
)}
</div>
- {validationError && (
- <LemonBanner
- className="mt-2"
- type="error"
- children={
- <div className="flex flex-row items-center justify-between">
- <div>
- Validation error:
- <br />
- {validationError}
- </div>
- <LemonButton
- children="Get help"
- type="secondary"
- onClick={() => {
- window.open(
- 'https://posthog.com/support?utm_medium=in-product&utm_campaign=join-modal-validation-error',
- '_blank'
- )
- }}
- />
- </div>
- }
- />
- )}
- {validationWarning && <LemonBanner className="mt-2" type="warning" children={validationWarning} />}
+ <JoinValidationStatus />
<LemonDivider className="mt-4 mb-4" />
<div className="flex flex-row gap-2 justify-end w-full">
- {isJoinValid ? (
- <>
- <LemonButton disabledReason="Join is valid">Join is valid</LemonButton>
- <LemonButton type="primary" htmlType="submit" loading={isViewLinkSubmitting}>
- Save join
- </LemonButton>
- </>
- ) : (
- <>
- <LemonButton htmlType="submit" loading={isViewLinkSubmitting} disabledReason={validationError}>
- Save join without validating
- </LemonButton>
+ <LemonButton type="secondary" onClick={toggleJoinTableModal}>
+ Close
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={isViewLinkSubmitting}
+ disabledReason={saveDisabledReason ?? undefined}
+ >
+ Save join
+ </LemonButton>
+ </div>
+ </Form>
+ )
+}
+
+function JoinValidationStatus(): JSX.Element | null {
+ const { joinValidation, keyTypeMismatchWarning } = useValues(viewLinkLogic)
+
+ return (
+ <div className="flex flex-col gap-2 mt-2 empty:hidden">
+ {keyTypeMismatchWarning && <LemonBanner type="warning">{keyTypeMismatchWarning}</LemonBanner>}
+ {joinValidation.status === 'validating' && (
+ <div className="flex items-center gap-2 text-secondary">
+ <Spinner />
+ <span>Validating join...</span>
+ </div>
+ )}
+ {joinValidation.status === 'valid' && (
+ <div className="flex items-center gap-2 text-success">
+ <IconCheckCircle />
+ <span>Join is valid</span>
+ </div>
+ )}
+ {joinValidation.status === 'valid' && joinValidation.msg && (
+ <LemonBanner type="warning">{joinValidation.msg}</LemonBanner>
+ )}
+ {joinValidation.status === 'error' && (
+ <LemonBanner type="error">
+ <div className="flex flex-row items-center justify-between">
+ <div>{joinValidation.msg || 'Could not validate the join.'}</div>
<LemonButton
- type="primary"
- onClick={validateJoin}
- loading={isJoinValidating}
- disabledReason={validationError || validationWarning}
+ type="secondary"
+ onClick={() => {
+ window.open(
+ 'https://posthog.com/support?utm_medium=in-product&utm_campaign=join-modal-validation-error',
+ '_blank'
+ )
+ }}
>
- Validate join
+ Get help
</LemonButton>
- </>
- )}
- </div>
- </Form>
+ </div>
+ </LemonBanner>
+ )}
+ </div>
)
}
diff --git a/frontend/src/scenes/data-warehouse/viewLinkLogic.test.tsx b/frontend/src/scenes/data-warehouse/viewLinkLogic.test.tsx
new file mode 100644
index 000000000000..2ec5f1170042
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/viewLinkLogic.test.tsx
@@ -0,0 +1,87 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { viewLinkLogic } from './viewLinkLogic'
+
+describe('viewLinkLogic', () => {
+ let logic: ReturnType<typeof viewLinkLogic.build>
+ let validateHandler: jest.Mock
+
+ beforeEach(() => {
+ validateHandler = jest.fn(() => [200, { is_valid: true, msg: null, hogql: null, results: [] }])
+ useMocks({
+ get: {
+ '/api/environments/:team_id/warehouse_view_link': { results: [] },
+ },
+ post: {
+ '/api/environments/:team_id/query/HogQLQuery': { results: [], columns: [] },
+ '/api/environments/:team_id/warehouse_view_link/validate': () => validateHandler(),
+ },
+ })
+ initKeaTests()
+ logic = viewLinkLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ const fillJoin = (): void => {
+ logic.actions.selectSourceTable('events')
+ logic.actions.selectJoiningTable('persons')
+ logic.actions.setViewLinkValue('source_table_key', 'uuid')
+ logic.actions.setViewLinkValue('joining_table_key', 'id')
+ }
+
+ it('debounces rapid changes into a single validation request', async () => {
+ fillJoin()
+
+ await expectLogic(logic).toDispatchActions(['validateJoinStarted', 'validateJoinSuccess'])
+ expect(validateHandler).toHaveBeenCalledTimes(1)
+ expect(logic.values.joinValidation.status).toBe('valid')
+ })
+
+ it('does not validate while any join input is missing', async () => {
+ logic.actions.selectSourceTable('events')
+ logic.actions.selectJoiningTable('persons')
+ logic.actions.setViewLinkValue('source_table_key', 'uuid')
+
+ await expectLogic(logic).delay(900).toFinishAllListeners()
+ expect(validateHandler).not.toHaveBeenCalled()
+ expect(logic.values.joinValidation.status).toBe('idle')
+ })
+
+ it('blocks saving only on a query error, not on warnings', async () => {
+ validateHandler.mockReturnValue([
+ 400,
+ { attr: null, code: 'QueryError', detail: 'Field not found: uuid', type: 'query_error', hogql: null },
+ ])
+ fillJoin()
+ await expectLogic(logic).toDispatchActions(['validateJoinFailure'])
+ expect(logic.values.saveDisabledReason).toBe('Fix the join keys before saving')
+ expect(logic.values.joinValidation.msg).toBe('Field not found: uuid')
+
+ validateHandler.mockReturnValue([
+ 200,
+ { is_valid: true, msg: 'Validation query returned no results', hogql: null, results: [] },
+ ])
+ logic.actions.setViewLinkValue('joining_table_key', 'id')
+ await expectLogic(logic).toDispatchActions(['validateJoinSuccess'])
+ expect(logic.values.saveDisabledReason).toBeNull()
+ expect(logic.values.joinValidation.msg).toBe('Validation query returned no results')
+ })
+
+ it('resets validation state when the modal closes', async () => {
+ logic.actions.toggleJoinTableModal()
+ fillJoin()
+ await expectLogic(logic).toDispatchActions(['validateJoinSuccess'])
+ expect(logic.values.joinValidation.status).toBe('valid')
+
+ logic.actions.toggleJoinTableModal()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.joinValidation.status).toBe('idle')
+ })
+})
diff --git a/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx b/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
index 725cf0deb7f0..a11325493ecb 100644
--- a/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, connect, isBreakpoint, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { subscriptions } from 'kea-subscriptions'
@@ -8,10 +8,10 @@ import api from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
-import { hogqlQuery } from '~/queries/query'
-import { DatabaseSchemaField } from '~/queries/schema/schema-general'
+import { performQuery } from '~/queries/query'
+import { DatabaseSchemaField, HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
-import { DataWarehouseViewLink } from '~/types'
+import { DataWarehouseViewLink, DataWarehouseViewLinkValidation } from '~/types'
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
@@ -27,6 +27,18 @@ const NEW_VIEW_LINK: DataWarehouseViewLink = {
field_name: undefined,
}
+export type JoinValidationStatus = 'idle' | 'validating' | 'valid' | 'error'
+
+export interface JoinValidationState {
+ status: JoinValidationStatus
+ msg: string | null
+ blocksSave: boolean
+ response: DataWarehouseViewLinkValidation | null
+}
+
+const IDLE_JOIN_VALIDATION: JoinValidationState = { status: 'idle', msg: null, blocksSave: false, response: null }
+const VALIDATE_JOIN_DEBOUNCE_MS = 700
+
export interface KeySelectOption {
value: string
label: JSX.Element
@@ -51,16 +63,17 @@ export interface viewLinkLogicValues {
error: string | null
fieldName: string
isJoinTableModalOpen: boolean
- isJoinValid: boolean
- isJoinValidating: boolean
isNewJoin: boolean
isViewLinkSubmitting: boolean
isViewLinkValid: boolean
joinToEdit: DataWarehouseViewLink | null
+ joinValidation: JoinValidationState
joiningIsUsingHogQLExpression: boolean
joiningTableKeys: KeySelectOption[]
joiningTablePreviewData: Record<string, any>[]
joiningTablePreviewLoading: boolean
+ keyTypeMismatchWarning: string | null
+ saveDisabledReason: string | null
selectedJoiningKey: string | null
selectedJoiningTable: DatabaseSchemaTable | undefined
selectedJoiningTableName: string | null
@@ -77,8 +90,6 @@ export interface viewLinkLogicValues {
label: string
value: string
}[]
- validationError: string | null
- validationWarning: string | null
viewLink: DataWarehouseViewLink
viewLinkAllErrors: Record<string, any>
viewLinkChanged: boolean
@@ -119,6 +130,9 @@ export interface viewLinkLogicActions {
loadSourceTablePreview: (tableName: string) => {
tableName: string
}
+ resetJoinValidation: () => {
+ value: true
+ }
resetViewLink: (values?: DataWarehouseViewLink) => {
values?: DataWarehouseViewLink
}
@@ -145,21 +159,15 @@ export interface viewLinkLogicActions {
setFieldName: (fieldName: string) => {
fieldName: string
}
- setIsJoinValid: (isValid: boolean) => {
- isValid: boolean
- }
setJoiningTablePreviewData: (data: Record<string, any>[]) => {
data: Record<string, any>[]
}
+ setKeyTypeMismatchWarning: (warning: string | null) => {
+ warning: string | null
+ }
setSourceTablePreviewData: (data: Record<string, any>[]) => {
data: Record<string, any>[]
}
- setValidationError: (errorMessage: string | null) => {
- errorMessage: string | null
- }
- setValidationWarning: (validationWarning: string | null) => {
- validationWarning: string | null
- }
setViewLinkManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -202,6 +210,19 @@ export interface viewLinkLogicActions {
key: string
}
validateJoin: () => void
+ validateJoinFailure: (
+ msg: string | null,
+ blocksSave: boolean
+ ) => {
+ blocksSave: boolean
+ msg: string | null
+ }
+ validateJoinStarted: () => {
+ value: true
+ }
+ validateJoinSuccess: (response: DataWarehouseViewLinkValidation) => {
+ response: DataWarehouseViewLinkValidation
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -234,6 +255,7 @@ export interface viewLinkLogicMeta {
selectedJoiningTableName: string | null,
fieldName: string
) => string | null
+ saveDisabledReason: (joinValidation: JoinValidationState) => string | null
}
}
@@ -267,10 +289,12 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
loadJoiningTablePreview: (tableName: string) => ({ tableName }),
setSourceTablePreviewData: (data: Record<string, any>[]) => ({ data }),
setJoiningTablePreviewData: (data: Record<string, any>[]) => ({ data }),
- setIsJoinValid: (isValid: boolean) => ({ isValid }),
- setValidationError: (errorMessage: string | null) => ({ errorMessage }),
- setValidationWarning: (validationWarning: string | null) => ({ validationWarning }),
+ setKeyTypeMismatchWarning: (warning: string | null) => ({ warning }),
validateJoin: () => {},
+ validateJoinStarted: true,
+ validateJoinSuccess: (response: DataWarehouseViewLinkValidation) => ({ response }),
+ validateJoinFailure: (msg: string | null, blocksSave: boolean) => ({ msg, blocksSave }),
+ resetJoinValidation: true,
checkKeyTypeMismatch: () => {},
})),
reducers({
@@ -293,21 +317,28 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
clearModalFields: () => false,
},
],
- isJoinValidating: [
- false as boolean,
+ joinValidation: [
+ IDLE_JOIN_VALIDATION,
{
- validateJoin: () => true,
- setIsJoinValid: () => false,
- },
- ],
- isJoinValid: [
- false as boolean,
- {
- setIsJoinValid: (_, { isValid }) => isValid,
- selectSourceKey: () => false,
- selectSourceTable: () => false,
- selectJoiningKey: () => false,
- selectJoiningTable: () => false,
+ validateJoinStarted: () => ({ ...IDLE_JOIN_VALIDATION, status: 'validating' as const }),
+ validateJoinSuccess: (_, { response }) => ({
+ status: response.is_valid ? ('valid' as const) : ('error' as const),
+ msg: response.msg ?? null,
+ blocksSave: false,
+ response,
+ }),
+ validateJoinFailure: (_, { msg, blocksSave }) => ({
+ status: 'error' as const,
+ msg,
+ blocksSave,
+ response: null,
+ }),
+ resetJoinValidation: () => IDLE_JOIN_VALIDATION,
+ selectSourceKey: () => IDLE_JOIN_VALIDATION,
+ selectSourceTable: () => IDLE_JOIN_VALIDATION,
+ selectJoiningKey: () => IDLE_JOIN_VALIDATION,
+ selectJoiningTable: () => IDLE_JOIN_VALIDATION,
+ clearModalFields: () => IDLE_JOIN_VALIDATION,
},
],
selectedSourceTableName: [
@@ -371,21 +402,10 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
clearModalFields: () => null,
},
],
- validationError: [
+ keyTypeMismatchWarning: [
null as null | string,
{
- setValidationError: (_, { errorMessage }) => errorMessage,
- clearModalFields: () => null,
- selectSourceKey: () => null,
- selectSourceTable: () => null,
- selectJoiningKey: () => null,
- selectJoiningTable: () => null,
- },
- ],
- validationWarning: [
- null as null | string,
- {
- setValidationWarning: (_, { validationWarning }) => validationWarning,
+ setKeyTypeMismatchWarning: (_, { warning }) => warning,
clearModalFields: () => null,
selectSourceKey: () => null,
selectSourceTable: () => null,
@@ -488,6 +508,7 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
if (join?.joining_table_name) {
actions.loadJoiningTablePreview(join.joining_table_name)
}
+ actions.validateJoin()
},
toggleEditJoinModal: ({ join }) => {
actions.setViewLinkValues(join)
@@ -497,26 +518,26 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
if (join.joining_table_name) {
actions.loadJoiningTablePreview(join.joining_table_name)
}
+ actions.validateJoin()
},
setViewLinkValue: ({ name }) => {
const fieldName = Array.isArray(name) ? name[0] : name
if (fieldName === 'joining_table_key' || fieldName === 'source_table_key') {
- actions.setIsJoinValid(false)
- actions.setValidationError(null)
- actions.setValidationWarning(null)
+ actions.resetJoinValidation()
+ actions.validateJoin()
}
},
selectSourceTable: async ({ selectedTableName }) => {
- actions.setIsJoinValid(false)
if (selectedTableName) {
actions.loadSourceTablePreview(selectedTableName)
}
+ actions.validateJoin()
},
selectJoiningTable: async ({ selectedTableName }) => {
- actions.setIsJoinValid(false)
if (selectedTableName) {
actions.loadJoiningTablePreview(selectedTableName)
}
+ actions.validateJoin()
},
checkKeyTypeMismatch: () => {
if (values.selectedSourceKey && values.selectedJoiningKey) {
@@ -528,18 +549,20 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
)
const sourceKeyDataType = sourceColumn?.type ?? 'unknown'
const joiningKeyDataType = joiningColumn?.type ?? 'unknown'
- const validationWarning =
+ const mismatchWarning =
sourceKeyDataType !== joiningKeyDataType
- ? `Key types don't match: Source table key is from type ${sourceKeyDataType} but joining table key is from type ${joiningKeyDataType}`
+ ? `Key types don't match: the source table key is of type ${sourceKeyDataType} but the joining table key is of type ${joiningKeyDataType}`
: null
- actions.setValidationWarning(validationWarning)
+ actions.setKeyTypeMismatchWarning(mismatchWarning)
}
},
selectSourceKey: () => {
actions.checkKeyTypeMismatch()
+ actions.validateJoin()
},
selectJoiningKey: () => {
actions.checkKeyTypeMismatch()
+ actions.validateJoin()
},
loadSourceTablePreview: async ({ tableName }) => {
await loadTablePreviewData(tableName, actions.setSourceTablePreviewData)
@@ -547,19 +570,20 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
loadJoiningTablePreview: async ({ tableName }) => {
await loadTablePreviewData(tableName, actions.setJoiningTablePreviewData)
},
- validateJoin: async () => {
+ validateJoin: async (_, breakpoint) => {
+ await breakpoint(VALIDATE_JOIN_DEBOUNCE_MS)
+
const sourceTableKey = values.viewLink.source_table_key
const joiningTableKey = values.viewLink.joining_table_key
-
if (
!values.selectedSourceTableName ||
!values.selectedJoiningTableName ||
!sourceTableKey ||
!joiningTableKey
) {
- actions.setIsJoinValid(false)
return
}
+ actions.validateJoinStarted()
try {
const response = await api.dataWarehouseViewLinks.validate({
source_table_name: values.selectedSourceTableName,
@@ -567,13 +591,21 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
joining_table_name: values.selectedJoiningTableName,
joining_table_key: joiningTableKey,
})
- actions.setIsJoinValid(response.is_valid)
- if (response.msg) {
- actions.setValidationWarning(response.msg)
- }
+ breakpoint()
+ actions.validateJoinSuccess(response)
} catch (error: any) {
- actions.setValidationError(error.detail)
- actions.setIsJoinValid(false)
+ if (isBreakpoint(error)) {
+ throw error
+ }
+ // Abort if a newer validation or a modal close superseded this listener, so a late
+ // failure can't overwrite the reset state or resurface in a later modal session.
+ breakpoint()
+ // Only a 400 proves the join itself is broken; infrastructure failures
+ // must not block saving.
+ actions.validateJoinFailure(
+ error.detail ?? 'Could not validate the join. You can still save it or try again.',
+ error.status === 400
+ )
}
},
})),
@@ -671,6 +703,13 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
return `SELECT ${tableAlias}.${fieldName || ''} FROM ${selectedSourceTableName} ${tableAlias}`
},
],
+ saveDisabledReason: [
+ (s) => [s.joinValidation],
+ (joinValidation: JoinValidationState): string | null =>
+ joinValidation.status === 'error' && joinValidation.blocksSave
+ ? 'Fix the join keys before saving'
+ : null,
+ ],
}),
subscriptions(({ actions, values }) => ({
isJoinTableModalOpen: (isOpen) => {
@@ -693,7 +732,12 @@ async function loadTablePreviewData(
setDataAction: (data: Record<string, any>[]) => void
): Promise<void> {
try {
- const response = await hogqlQuery(hogql`SELECT * FROM ${hogql.identifier(tableName)} LIMIT 10`)
+ // 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]]))
)