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 SQL variable controls (#78976)

Marius Andra41b84ca8fa1f
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/NewVariableModal.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/NewVariableModal.tsx
index 66d6e04ad27f..ea4e485c9c1c 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/NewVariableModal.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/NewVariableModal.tsx
@@ -8,12 +8,14 @@ import { VariableType } from '../../types'
import { variableDataLogic } from './variableDataLogic'
import { VariableForm } from './VariableForm'
import { variableModalLogic } from './variableModalLogic'
+import { variablesLogic } from './variablesLogic'
export const NewVariableModal = (): JSX.Element => {
const { closeModal, updateVariable, save, openNewVariableModal, changeTypeExistingVariable } =
useActions(variableModalLogic)
const { isModalOpen, variable, modalType, insightsUsingVariable, insightsLoading, isSaving } =
useValues(variableModalLogic)
+ const { query } = useValues(variablesLogic)
const { deleteVariable } = useActions(variableDataLogic)
const title = modalType === 'new' ? `New ${variable.type} variable` : `Editing ${variable.name}`
@@ -53,22 +55,20 @@ export const NewVariableModal = (): JSX.Element => {
onClose={closeModal}
maxWidth={modalType === 'existing' && insightsUsingVariable.length > 0 ? '60rem' : '30rem'}
footer={
- variable.type !== 'Date' && (
- <div className="flex flex-1 justify-end gap-2">
- {modalType === 'existing' && (
- <LemonButton type="secondary" status="danger" onClick={handleDelete} disabled={isSaving}>
- Delete variable
- </LemonButton>
- )}
- <div className="flex-1" />
- <LemonButton type="secondary" onClick={closeModal} disabled={isSaving}>
- Close
+ <div className="flex flex-1 justify-end gap-2">
+ {modalType === 'existing' && (
+ <LemonButton type="secondary" status="danger" onClick={handleDelete} disabled={isSaving}>
+ Delete variable
</LemonButton>
- <LemonButton type="primary" onClick={() => save()} loading={isSaving}>
- Save
- </LemonButton>
- </div>
- )
+ )}
+ <div className="flex-1" />
+ <LemonButton type="secondary" onClick={closeModal} disabled={isSaving}>
+ Close
+ </LemonButton>
+ <LemonButton type="primary" onClick={() => save()} loading={isSaving}>
+ Save
+ </LemonButton>
+ </div>
}
>
<VariableForm
@@ -77,6 +77,7 @@ export const NewVariableModal = (): JSX.Element => {
onSave={save}
modalType={modalType}
onTypeChange={handleTypeChange}
+ defaultValuesQueryConnectionId={query?.source?.connectionId ?? null}
/>
{modalType === 'existing' && (
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.test.ts
index ba73eefd5582..75df35a87bd4 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.test.ts
@@ -1,5 +1,12 @@
import { ListVariable } from '../../types'
import { coerceListVariableValue, getListVariableValues } from './VariableFields'
+import {
+ formatRelativeDateValue,
+ getListVariableSelectedValues,
+ isRelativeDateValue,
+ normalizeRelativeDateAmount,
+ parseRelativeDateValue,
+} from './variableUtils'
const listVariable = (values: unknown): ListVariable =>
({
@@ -35,4 +42,40 @@ describe('VariableFields', () => {
])('coerceListVariableValue: %s', (_name, value, expected) => {
expect(coerceListVariableValue(value)).toBe(expected)
})
+
+ test.each([
+ ['single value stays scalar-shaped', false, ['first', 'second'], ['first']],
+ ['multiple values are preserved', true, ['first', 'second'], ['first', 'second']],
+ ['a scalar default becomes one selected value', true, 'first', ['first']],
+ ['an empty default has no selected values', true, '', []],
+ ])('getListVariableSelectedValues: %s', (_name, isMulti, defaultValue, expected) => {
+ expect(
+ getListVariableSelectedValues({
+ ...listVariable(['first', 'second']),
+ is_multi: isMulti,
+ default_value: defaultValue,
+ })
+ ).toEqual(expected)
+ })
+
+ test.each([
+ ['a rolling offset', '-30d', true, { amount: 30, unit: 'd' }, '30 days ago'],
+ ['the current time', '-0h', true, { amount: 0, unit: 'h' }, 'Now'],
+ ['a fixed date', '2026-08-06', false, null, '2026-08-06'],
+ ['a unit only the backend resolves', '-1q', false, null, '-1q'],
+ ['a period boundary only the backend resolves', 'mStart', false, null, 'mStart'],
+ ])('relative date helpers: %s', (_name, value, isRelative, parsed, formatted) => {
+ expect(isRelativeDateValue(value)).toBe(isRelative)
+ expect(parseRelativeDateValue(value)).toEqual(parsed)
+ expect(formatRelativeDateValue(value)).toBe(formatted)
+ })
+
+ test.each([
+ ['whole number', 30, 30],
+ ['fractional number', 1.5, 2],
+ ['negative number', -5, 0],
+ ['empty number input', Number.NaN, 0],
+ ])('normalizeRelativeDateAmount: %s', (_name, amount, expected) => {
+ expect(normalizeRelativeDateAmount(amount)).toBe(expected)
+ })
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx
index 67c2356a8da7..57ef4dab4670 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx
@@ -1,6 +1,23 @@
-import { LemonInput, LemonInputSelect, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+import { useActions, useValues } from 'kea'
+
+import {
+ LemonButton,
+ LemonInput,
+ LemonInputSelect,
+ LemonSegmentedButton,
+ LemonSelect,
+ LemonSwitch,
+} from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'
+import {
+ POSTHOG_WAREHOUSE,
+ connectionSelectorLogic,
+ getConnectionOptionLabel,
+} from 'scenes/data-warehouse/editor/connectionSelectorLogic'
import {
BooleanVariable,
@@ -12,6 +29,18 @@ import {
VariableType,
} from '../../types'
import { VariableCalendar } from './VariableCalendar'
+import {
+ RelativeDateUnit,
+ formatRelativeDateValue,
+ getListVariableSelectedValues,
+ getListVariableValues,
+ isRelativeDateValue,
+ normalizeRelativeDateAmount,
+ parseRelativeDateValue,
+} from './variableUtils'
+import { getStaticVariableOptions, getValuesQueryKey, variableValuesLogic } from './variableValuesLogic'
+
+export { coerceListVariableValue, getListVariableValues } from './variableUtils'
export const VARIABLE_TYPE_OPTIONS: Array<{ value: VariableType; label: string }> = [
{ value: 'String', label: 'String' },
@@ -43,46 +72,6 @@ export const formatVariableReference = (codeName: string): string => {
return `{variables.${codeName}}`
}
-// `values` is backed by a JSONField, so API-created variables can hold entries that
-// aren't strings — e.g. option-shaped objects like {label, value} from migration
-// scripts. Objects aren't valid React children (React error #31), so everything must
-// be coerced to a string before rendering.
-export const coerceListVariableValue = (value: unknown): string | null => {
- if (value == null) {
- return null
- }
- if (typeof value === 'string') {
- return value
- }
- if (typeof value === 'number' || typeof value === 'boolean') {
- return String(value)
- }
- if (typeof value === 'object' && !Array.isArray(value)) {
- const record = value as Record<string, unknown>
- for (const key of ['value', 'label']) {
- const inner = record[key]
- if (typeof inner === 'string') {
- return inner
- }
- if (typeof inner === 'number' || typeof inner === 'boolean') {
- return String(inner)
- }
- }
- }
- try {
- return JSON.stringify(value) ?? null
- } catch {
- return String(value)
- }
-}
-
-// `values` can also be non-array data for older records, so coerce defensively
-// before mapping/rendering to avoid runtime crashes.
-export const getListVariableValues = (variable: ListVariable): string[] =>
- Array.isArray(variable.values)
- ? variable.values.map(coerceListVariableValue).filter((value): value is string => value !== null)
- : []
-
// Field components for direct prop binding (used in modal)
export interface DirectFieldProps<T extends Variable = Variable> {
variable: T
@@ -131,74 +120,297 @@ export const ListValuesField = ({ variable, updateVariable }: DirectFieldProps<L
/>
)
-export const ListDefaultField = ({ variable, updateVariable }: DirectFieldProps<ListVariable>): JSX.Element => (
- <LemonSelect
- className="w-full"
- placeholder="Select default value"
- value={coerceListVariableValue(variable.default_value)}
- options={getListVariableValues(variable).map((n: string) => ({ label: n, value: n }))}
- onChange={(value) => updateVariable({ ...variable, default_value: value ?? '' })}
- allowClear
- dropdownMaxContentWidth
- />
-)
+interface ListVariableSelectProps {
+ variable: ListVariable
+ disabledReason?: string | false
+ loadOnMount?: boolean
+ onBlur?: () => void
+ onChange: (value: string | string[]) => void
+ selectedValues?: string[]
+ size?: 'small' | 'medium'
+}
-export const DateField = ({ variable, updateVariable, onSave }: DirectFieldProps<DateVariable>): JSX.Element => (
- <VariableCalendar
- value={dayjs(variable.default_value)}
- rawValue={variable.default_value}
- updateVariable={(date) => {
- updateVariable({ ...variable, default_value: date })
- // calendar is a special case to reuse LemonCalendarSelect
- onSave()
- }}
- />
-)
+export const ListVariableSelect = ({
+ variable,
+ disabledReason,
+ loadOnMount = true,
+ onBlur,
+ onChange,
+ selectedValues = getListVariableSelectedValues(variable),
+ size,
+}: ListVariableSelectProps): JSX.Element => {
+ const logic = variableValuesLogic({ variable, loadOnMount })
+ const { loadVariableOptions } = useActions(logic)
+ const { requestedValuesQueryKey, variableOptions, variableOptionsError, variableOptionsLoading } = useValues(logic)
+ const isCurrentQuery = requestedValuesQueryKey === getValuesQueryKey(variable)
+ const options =
+ variable.values_query == null ? getStaticVariableOptions(variable) : isCurrentQuery ? variableOptions : []
+ const currentError = isCurrentQuery ? variableOptionsError : null
-// Helper to narrow variable types based on the type property
-function withTypedVariable<T extends Variable>(
- variable: Variable,
- updateVariable: (variable: Variable) => void
-): { variable: T; updateVariable: (variable: T) => void } {
- return {
- variable: variable as T,
- updateVariable: updateVariable as (variable: T) => void,
- }
+ return (
+ <LemonInputSelect
+ className="w-full"
+ mode={variable.is_multi ? 'multiple' : 'single'}
+ value={selectedValues}
+ options={options.map((option) => ({ key: option.value, label: option.label }))}
+ onBlur={onBlur}
+ onChange={(values) => onChange(variable.is_multi ? values : (values[0] ?? ''))}
+ placeholder={variableOptionsLoading ? 'Loading options...' : 'Select a value'}
+ emptyStateComponent={currentError ? "Couldn't load options. Check the query, then try again." : undefined}
+ status={currentError ? 'danger' : 'default'}
+ loading={variableOptionsLoading}
+ disabledReason={disabledReason || undefined}
+ size={size}
+ displayMode={variable.is_multi ? 'count' : 'snacks'}
+ bulkActions={variable.is_multi ? 'select-and-clear-all' : undefined}
+ action={
+ !variable.is_multi && selectedValues.length > 0
+ ? {
+ children: 'Clear selection',
+ onClick: () => onChange(''),
+ }
+ : variable.values_query?.trim()
+ ? {
+ children: 'Reload options',
+ onClick: () => loadVariableOptions(variable),
+ loading: variableOptionsLoading,
+ }
+ : undefined
+ }
+ fullWidth
+ />
+ )
}
-export const renderDefaultValueFields = (
- variableType: VariableType,
- variable: Variable,
- updateVariable: (variable: Variable) => void,
- onSave: () => void
-): JSX.Element => {
- switch (variableType) {
- case 'String': {
- const props = withTypedVariable<StringVariable>(variable, updateVariable)
- return <StringField {...props} onSave={onSave} />
- }
- case 'Number': {
- const props = withTypedVariable<NumberVariable>(variable, updateVariable)
- return <NumberField {...props} onSave={onSave} />
- }
- case 'Boolean': {
- const props = withTypedVariable<BooleanVariable>(variable, updateVariable)
- return <BooleanField {...props} onSave={onSave} />
- }
- case 'List': {
- const props = withTypedVariable<ListVariable>(variable, updateVariable)
- return (
+export const ListVariableFields = ({
+ variable,
+ updateVariable,
+ defaultValuesQueryConnectionId,
+}: DirectFieldProps<ListVariable> & { defaultValuesQueryConnectionId?: string | null }): JSX.Element => {
+ const isQueryBacked = variable.values_query != null
+ const logic = variableValuesLogic({
+ variable,
+ loadOnMount: isQueryBacked && Boolean(variable.values_query?.trim()),
+ })
+ const { loadVariableOptions } = useActions(logic)
+ const { requestedValuesQueryKey, variableOptions, variableOptionsError, variableOptionsLoading } = useValues(logic)
+ const { connectionOptions } = useValues(connectionSelectorLogic())
+ const { maybeLoadConnectionOptions } = useActions(connectionSelectorLogic())
+ useOnMountEffect(() => maybeLoadConnectionOptions())
+ const isCurrentQuery = requestedValuesQueryKey === getValuesQueryKey(variable)
+ const loadedOptions = isQueryBacked && isCurrentQuery ? variableOptions : []
+ const availableOptions = isQueryBacked ? loadedOptions : getStaticVariableOptions(variable)
+ const currentError = isCurrentQuery ? variableOptionsError : null
+ const defaultValues = getListVariableSelectedValues({ ...variable, value: undefined })
+ const showConnectionSelector = (connectionOptions?.length ?? 0) > 0 || Boolean(variable.values_query_connection_id)
+ const hasCustomLabels = loadedOptions.some((option) => option.label !== option.value)
+
+ return (
+ <>
+ <LemonField.Pure label="Options source" className="gap-1">
+ <LemonSegmentedButton
+ className="w-full"
+ value={isQueryBacked ? 'query' : 'static'}
+ onChange={(source) =>
+ updateVariable({
+ ...variable,
+ values_query: source === 'query' ? '' : null,
+ values_query_connection_id:
+ source === 'query'
+ ? (variable.values_query_connection_id ?? defaultValuesQueryConnectionId ?? null)
+ : null,
+ default_value: variable.is_multi ? [] : '',
+ })
+ }
+ options={[
+ { value: 'static', label: 'Static options' },
+ { value: 'query', label: 'HogQL query' },
+ ]}
+ />
+ </LemonField.Pure>
+ {isQueryBacked ? (
<>
- <ListValuesField {...props} onSave={onSave} />
- <ListDefaultField {...props} onSave={onSave} />
+ {showConnectionSelector && (
+ <LemonField.Pure label="Connection" className="gap-1">
+ <LemonSelect
+ value={variable.values_query_connection_id ?? POSTHOG_WAREHOUSE}
+ onChange={(value) =>
+ updateVariable({
+ ...variable,
+ values_query_connection_id: value === POSTHOG_WAREHOUSE ? null : value,
+ })
+ }
+ options={[
+ { value: POSTHOG_WAREHOUSE, label: 'PostHog (ClickHouse)' },
+ ...(connectionOptions ?? []).map((source) => ({
+ value: source.id,
+ label: getConnectionOptionLabel(source),
+ })),
+ ]}
+ fullWidth
+ />
+ </LemonField.Pure>
+ )}
+ <LemonField.Pure
+ label="Options query"
+ className="gap-1"
+ info="The first column supplies the option values. An optional second column supplies their display labels. Queries without a LIMIT return up to 100 rows. Options load when the variable is shown, and results are cached for a few minutes."
+ >
+ <CodeEditorResizeable
+ language="hogQL"
+ value={variable.values_query ?? ''}
+ onChange={(value) => updateVariable({ ...variable, values_query: value ?? '' })}
+ minHeight="6rem"
+ maxHeight="40vh"
+ />
+ <div className="flex items-center justify-end gap-2">
+ {currentError ? (
+ <span className="text-danger text-xs">
+ Couldn't load options. Check the query, then try again.
+ </span>
+ ) : loadedOptions.length > 0 ? (
+ <span className="text-success text-xs">
+ Loaded {loadedOptions.length} option{loadedOptions.length === 1 ? '' : 's'}
+ </span>
+ ) : null}
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ onClick={() => loadVariableOptions(variable)}
+ loading={variableOptionsLoading}
+ disabledReason={!variable.values_query?.trim() ? 'Enter a query first' : undefined}
+ >
+ Preview options
+ </LemonButton>
+ </div>
+ {!currentError && loadedOptions.length > 0 ? (
+ <ul className="border rounded max-h-40 overflow-y-auto m-0 p-0 list-none">
+ {hasCustomLabels && (
+ <li className="flex gap-2 px-2 py-1 text-xs font-medium text-secondary border-b sticky top-0 bg-bg-light">
+ <span className="flex-1 min-w-0">Value</span>
+ <span className="flex-1 min-w-0">Label</span>
+ </li>
+ )}
+ {loadedOptions.map((option) => (
+ <li
+ key={option.value}
+ className="flex gap-2 px-2 py-1 text-xs border-b last:border-b-0"
+ >
+ <span className="flex-1 min-w-0 truncate">{option.value}</span>
+ {hasCustomLabels && (
+ <span className="flex-1 min-w-0 text-secondary truncate">
+ {option.label}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </LemonField.Pure>
</>
- )
- }
- case 'Date': {
- const props = withTypedVariable<DateVariable>(variable, updateVariable)
- return <DateField {...props} onSave={onSave} />
- }
- default:
- throw new Error(`Unsupported variable type: ${variableType}`)
- }
+ ) : (
+ <LemonField.Pure label="Options" className="gap-1">
+ <ListValuesField variable={variable} updateVariable={updateVariable} onSave={() => {}} />
+ </LemonField.Pure>
+ )}
+ <LemonSwitch
+ label="Allow multiple selections"
+ checked={Boolean(variable.is_multi)}
+ onChange={(isMulti) => {
+ const normalizedDefault = isMulti ? defaultValues : (defaultValues[0] ?? '')
+ updateVariable({ ...variable, is_multi: isMulti, default_value: normalizedDefault })
+ }}
+ bordered
+ />
+ <LemonField.Pure label="Default value" className="gap-1">
+ <LemonInputSelect
+ className="w-full"
+ mode={variable.is_multi ? 'multiple' : 'single'}
+ value={defaultValues}
+ options={availableOptions.map((option) => ({ key: option.value, label: option.label }))}
+ onChange={(values) =>
+ updateVariable({
+ ...variable,
+ default_value: variable.is_multi ? values : (values[0] ?? ''),
+ })
+ }
+ placeholder={variableOptionsLoading ? 'Loading options...' : 'Select a default value'}
+ loading={variableOptionsLoading}
+ emptyStateComponent={isQueryBacked ? 'Preview the query to load options.' : undefined}
+ fullWidth
+ />
+ </LemonField.Pure>
+ </>
+ )
+}
+
+const RELATIVE_DATE_UNITS: Array<{ value: RelativeDateUnit; label: string }> = [
+ { value: 'h', label: 'hours' },
+ { value: 'd', label: 'days' },
+ { value: 'w', label: 'weeks' },
+ { value: 'm', label: 'months' },
+ { value: 'y', label: 'years' },
+]
+
+export const DateField = ({ variable, updateVariable }: DirectFieldProps<DateVariable>): JSX.Element => {
+ const isRelative = isRelativeDateValue(variable.default_value)
+ const relativeValue = parseRelativeDateValue(variable.default_value) ?? { amount: 0, unit: 'd' as RelativeDateUnit }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSegmentedButton
+ className="w-full"
+ value={isRelative ? 'relative' : 'fixed'}
+ onChange={(mode) =>
+ updateVariable({
+ ...variable,
+ default_value: mode === 'relative' ? '-0d' : dayjs().format('YYYY-MM-DD HH:mm:00'),
+ })
+ }
+ options={[
+ { value: 'fixed', label: 'Fixed date' },
+ { value: 'relative', label: 'Relative date' },
+ ]}
+ />
+ {isRelative ? (
+ <div className="flex items-center gap-2">
+ <LemonInput
+ type="number"
+ min={0}
+ step={1}
+ value={relativeValue.amount}
+ onChange={(amount) =>
+ updateVariable({
+ ...variable,
+ default_value: `-${normalizeRelativeDateAmount(amount)}${relativeValue.unit}`,
+ })
+ }
+ />
+ <LemonSelect<RelativeDateUnit>
+ className="grow"
+ value={relativeValue.unit}
+ options={RELATIVE_DATE_UNITS}
+ onChange={(unit) =>
+ updateVariable({
+ ...variable,
+ default_value: `-${relativeValue.amount}${unit ?? 'd'}`,
+ })
+ }
+ />
+ <span className="whitespace-nowrap text-secondary">ago</span>
+ </div>
+ ) : (
+ <VariableCalendar
+ value={dayjs(variable.default_value)}
+ rawValue={variable.default_value}
+ updateVariable={(date) => updateVariable({ ...variable, default_value: date })}
+ />
+ )}
+ {isRelative && (
+ <span className="text-xs text-secondary">
+ Current value: {formatRelativeDateValue(variable.default_value)}
+ </span>
+ )}
+ </div>
+ )
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableForm.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableForm.tsx
index f2200de41bc5..bd5baa913c87 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableForm.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableForm.tsx
@@ -10,8 +10,7 @@ import {
BooleanField,
DateField,
DirectFieldProps,
- ListDefaultField,
- ListValuesField,
+ ListVariableFields,
NumberField,
StringField,
VARIABLE_TYPE_OPTIONS,
@@ -33,11 +32,17 @@ function renderField<T extends Variable>(
)
}
-const renderVariableSpecificFields = (
- variable: Variable,
- updateVariable: (variable: Variable) => void,
+export const VariableSpecificFields = ({
+ variable,
+ updateVariable,
+ onSave,
+ defaultValuesQueryConnectionId,
+}: {
+ variable: Variable
+ updateVariable: (variable: Variable) => void
onSave: () => void
-): JSX.Element => {
+ defaultValuesQueryConnectionId?: string | null
+}): JSX.Element => {
switch (variable.type) {
case 'String':
return renderField(StringField, variable, updateVariable, onSave, 'Default value')
@@ -47,10 +52,12 @@ const renderVariableSpecificFields = (
return renderField(BooleanField, variable, updateVariable, onSave, 'Default value')
case 'List':
return (
- <>
- {renderField(ListValuesField, variable, updateVariable, onSave, 'Values')}
- {renderField(ListDefaultField, variable, updateVariable, onSave, 'Default value')}
- </>
+ <ListVariableFields
+ variable={variable}
+ updateVariable={updateVariable}
+ onSave={onSave}
+ defaultValuesQueryConnectionId={defaultValuesQueryConnectionId}
+ />
)
case 'Date':
return renderField(DateField, variable, updateVariable, onSave, 'Default value')
@@ -63,9 +70,16 @@ export interface VariableFormProps {
onSave: () => void
modalType: 'new' | 'existing'
onTypeChange: (variableType: VariableType) => void
+ defaultValuesQueryConnectionId?: string | null
}
-export const VariableForm = ({ variable, updateVariable, onSave, onTypeChange }: VariableFormProps): JSX.Element => {
+export const VariableForm = ({
+ variable,
+ updateVariable,
+ onSave,
+ onTypeChange,
+ defaultValuesQueryConnectionId,
+}: VariableFormProps): JSX.Element => {
const codeNameFallback = getCodeName(variable.name)
const referenceCodeName = variable.code_name || codeNameFallback
const nameLabel = (
@@ -112,7 +126,12 @@ export const VariableForm = ({ variable, updateVariable, onSave, onTypeChange }:
options={VARIABLE_TYPE_OPTIONS}
/>
</LemonField.Pure>
- {renderVariableSpecificFields(variable, updateVariable, onSave)}
+ <VariableSpecificFields
+ variable={variable}
+ updateVariable={updateVariable}
+ onSave={onSave}
+ defaultValuesQueryConnectionId={defaultValuesQueryConnectionId}
+ />
</div>
)
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx
index d16e4121c05c..7beb5fce42d6 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx
@@ -9,7 +9,6 @@ import {
LemonDivider,
LemonInput,
LemonSegmentedButton,
- LemonSelect,
LemonSwitch,
Popover,
lemonToast,
@@ -23,12 +22,28 @@ import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { dataVisualizationLogic } from '../../dataVisualizationLogic'
-import { Variable } from '../../types'
+import { DateVariable, ListVariable, Variable } from '../../types'
+import { inlineListVariableSelectLogic } from './inlineListVariableSelectLogic'
import { NewVariableModal } from './NewVariableModal'
-import { VariableCalendar } from './VariableCalendar'
-import { coerceListVariableValue, getListVariableValues } from './VariableFields'
+import { DateField, ListVariableSelect } from './VariableFields'
import { variableModalLogic } from './variableModalLogic'
import { variablesLogic } from './variablesLogic'
+import { formatRelativeDateValue, getListVariableSelectedValues, isRelativeDateValue } from './variableUtils'
+
+const getVariableDisplayValue = (variable: Variable): string => {
+ const value = variable.value ?? variable.default_value
+ if (variable.type === 'List') {
+ const selectedValues = getListVariableSelectedValues(variable)
+ if (variable.is_multi && selectedValues.length > 1) {
+ return `${selectedValues.length} selected`
+ }
+ return selectedValues[0] ?? ''
+ }
+ if (variable.type === 'Date' && typeof value === 'string' && isRelativeDateValue(value)) {
+ return formatRelativeDateValue(value)
+ }
+ return String(value ?? '')
+}
export const VariablesForDashboard = (): JSX.Element => {
const { effectiveVariablesAndAssociatedInsights } = useValues(dashboardLogic)
@@ -106,7 +121,7 @@ export const VariableInput = ({
variableSettingsOnClick,
onInsertAtCursor,
}: VariableInputProps): JSX.Element => {
- const [localInputValue, setLocalInputValue] = useState<string>(() => {
+ const [localInputValue, setLocalInputValue] = useState<string | string[]>(() => {
const val = variable.value ?? variable.default_value
if (variable.type === 'Number' && !val) {
@@ -122,7 +137,7 @@ export const VariableInput = ({
}
if (variable.type === 'List') {
- return coerceListVariableValue(val) ?? ''
+ return getListVariableSelectedValues(variable)
}
return String(val ?? '')
@@ -146,7 +161,7 @@ export const VariableInput = ({
inputRef={inputRef}
placeholder="Value..."
className="flex flex-1"
- value={localInputValue}
+ value={String(localInputValue)}
onChange={(value) => setLocalInputValue(value)}
onPressEnter={() => {
onChange(variable.id, localInputValue, isNull)
@@ -171,7 +186,7 @@ export const VariableInput = ({
{variable.type === 'Boolean' && (
<LemonSegmentedButton
className="grow"
- value={localInputValue}
+ value={String(localInputValue)}
onChange={(value) => setLocalInputValue(value)}
options={[
{
@@ -186,38 +201,34 @@ export const VariableInput = ({
/>
)}
{variable.type === 'List' && (
- <LemonSelect
- className="grow"
- value={localInputValue}
- onChange={(value) => setLocalInputValue(String(value))}
- options={getListVariableValues(variable).map((n) => ({ label: n, value: n }))}
+ <ListVariableSelect
+ variable={variable}
+ selectedValues={(Array.isArray(localInputValue) ? localInputValue : [localInputValue]).filter(
+ (value) => value !== ''
+ )}
+ onChange={setLocalInputValue}
/>
)}
{variable.type === 'Date' && (
- <VariableCalendar
- value={dayjs(localInputValue)}
- rawValue={localInputValue}
- updateVariable={(date) => {
- onChange(variable.id, date, isNull)
- closePopover()
- }}
+ <DateField
+ variable={{ ...variable, default_value: String(localInputValue) } as DateVariable}
+ updateVariable={(updatedVariable) => setLocalInputValue(updatedVariable.default_value)}
+ onSave={() => {}}
/>
)}
- {variable.type !== 'Date' && (
- <LemonButton
- type="primary"
- onClick={() => {
- onChange(
- variable.id,
- variable.type === 'Number' ? Number(localInputValue) : localInputValue,
- isNull
- )
- closePopover()
- }}
- >
- {showEditingUI ? 'Save' : 'Update'}
- </LemonButton>
- )}
+ <LemonButton
+ type="primary"
+ onClick={() => {
+ onChange(
+ variable.id,
+ variable.type === 'Number' ? Number(localInputValue) : localInputValue,
+ isNull
+ )
+ closePopover()
+ }}
+ >
+ {showEditingUI ? 'Save' : 'Update'}
+ </LemonButton>
</div>
{showEditingUI ? (
<>
@@ -321,6 +332,40 @@ interface VariableComponentProps {
size?: 'small' | 'medium'
}
+interface BufferedMultiListVariableSelectProps {
+ variable: ListVariable
+ disabledReason?: string | false
+ onChange: (variableId: string, value: string[], isNull: boolean) => void
+ size?: 'small' | 'medium'
+}
+
+const BufferedMultiListVariableSelect = ({
+ variable,
+ disabledReason,
+ onChange,
+ size,
+}: BufferedMultiListVariableSelectProps): JSX.Element => {
+ const selectedValues = variable.isNull ? [] : getListVariableSelectedValues(variable)
+ const logic = inlineListVariableSelectLogic({
+ variableId: variable.id,
+ selectedValues,
+ onChange: (values) => onChange(variable.id, values, values.length === 0),
+ })
+ const { selectedValues: bufferedValues } = useValues(logic)
+ const { commitSelectedValues, setSelectedValues } = useActions(logic)
+
+ return (
+ <ListVariableSelect
+ variable={variable}
+ disabledReason={disabledReason}
+ selectedValues={bufferedValues}
+ onChange={(value) => setSelectedValues(Array.isArray(value) ? value : value ? [value] : [])}
+ onBlur={commitSelectedValues}
+ size={size}
+ />
+ )
+}
+
export const VariableComponent = ({
variable,
showEditingUI,
@@ -346,16 +391,25 @@ export const VariableComponent = ({
// Don't show the popover overlay for list variables not in edit mode
if (!showEditingUI && variable.type === 'List') {
+ const disabledReason = variableOverridesAreSet && 'Discard dashboard variables to change'
return (
<LemonField.Pure label={variable.name} className="gap-0" info={tooltip}>
- <LemonSelect
- disabledReason={variableOverridesAreSet && 'Discard dashboard variables to change'}
- value={variable.isNull ? null : coerceListVariableValue(variable.value ?? variable.default_value)}
- onChange={(value) => onChange(variable.id, value, !value)}
- options={getListVariableValues(variable).map((n) => ({ label: n, value: n }))}
- size={size}
- allowClear
- />
+ {variable.is_multi ? (
+ <BufferedMultiListVariableSelect
+ variable={variable}
+ disabledReason={disabledReason}
+ onChange={onChange}
+ size={size}
+ />
+ ) : (
+ <ListVariableSelect
+ variable={variable}
+ disabledReason={disabledReason}
+ selectedValues={variable.isNull ? [] : getListVariableSelectedValues(variable)}
+ onChange={(value) => onChange(variable.id, value, value === '')}
+ size={size}
+ />
+ )}
</LemonField.Pure>
)
}
@@ -394,11 +448,7 @@ export const VariableComponent = ({
disabledReason={variableOverridesAreSet && 'Discard dashboard variables to change'}
size={size}
>
- {variable.isNull
- ? 'Set to null'
- : (variable.value?.toString() || variable.default_value?.toString() || '') === ''
- ? emptyState
- : (variable.value?.toString() ?? variable.default_value?.toString())}
+ {variable.isNull ? 'Set to null' : getVariableDisplayValue(variable) || emptyState}
</LemonButton>
{showEditingUI && (
<LemonButton
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/inlineListVariableSelectLogic.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/inlineListVariableSelectLogic.test.ts
new file mode 100644
index 000000000000..d95f6d3d884d
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/inlineListVariableSelectLogic.test.ts
@@ -0,0 +1,42 @@
+import { initKeaTests } from '~/test/init'
+
+import { inlineListVariableSelectLogic } from './inlineListVariableSelectLogic'
+
+describe('inlineListVariableSelectLogic', () => {
+ let logic: ReturnType<typeof inlineListVariableSelectLogic.build>
+ let onChange: jest.Mock
+
+ beforeEach(() => {
+ initKeaTests()
+ onChange = jest.fn()
+ logic = inlineListVariableSelectLogic({
+ variableId: 'variable-id',
+ selectedValues: [],
+ onChange,
+ })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('commits several option changes once when the selection closes', () => {
+ logic.actions.setSelectedValues(['pageview'])
+ logic.actions.setSelectedValues(['pageview', 'signup'])
+ inlineListVariableSelectLogic({
+ variableId: 'variable-id',
+ selectedValues: [],
+ onChange,
+ })
+
+ expect(logic.values.selectedValues).toEqual(['pageview', 'signup'])
+ expect(onChange).not.toHaveBeenCalled()
+
+ logic.actions.commitSelectedValues()
+ logic.actions.commitSelectedValues()
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange).toHaveBeenCalledWith(['pageview', 'signup'])
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/inlineListVariableSelectLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/inlineListVariableSelectLogic.ts
new file mode 100644
index 000000000000..b1bac26572fa
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/inlineListVariableSelectLogic.ts
@@ -0,0 +1,83 @@
+import { LogicWrapper, MakeLogicType, actions, kea, key, listeners, path, props, propsChanged, reducers } from 'kea'
+
+export interface InlineListVariableSelectLogicProps {
+ variableId: string
+ selectedValues: string[]
+ onChange: (selectedValues: string[]) => void
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface inlineListVariableSelectLogicValues {
+ hasChanges: boolean
+ selectedValues: string[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface inlineListVariableSelectLogicActions {
+ commitSelectedValues: () => {
+ hasChanges: boolean
+ selectedValues: string[]
+ }
+ resetSelectedValues: (selectedValues: string[]) => {
+ selectedValues: string[]
+ }
+ setSelectedValues: (selectedValues: string[]) => {
+ selectedValues: string[]
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface inlineListVariableSelectLogicMeta {
+ key: string
+}
+
+export type inlineListVariableSelectLogicType = MakeLogicType<
+ inlineListVariableSelectLogicValues,
+ inlineListVariableSelectLogicActions,
+ InlineListVariableSelectLogicProps,
+ inlineListVariableSelectLogicMeta
+>
+
+const equalSelectedValues = (left: string[], right: string[]): boolean =>
+ left.length === right.length && left.every((value, index) => value === right[index])
+
+export const inlineListVariableSelectLogic: LogicWrapper<inlineListVariableSelectLogicType> =
+ kea<inlineListVariableSelectLogicType>([
+ props({} as InlineListVariableSelectLogicProps),
+ key((props) => props.variableId),
+ path((key) => ['queries', 'nodes', 'DataVisualization', 'Variables', 'inlineListVariableSelectLogic', key]),
+ actions(({ values }) => ({
+ setSelectedValues: (selectedValues: string[]) => ({ selectedValues }),
+ resetSelectedValues: (selectedValues: string[]) => ({ selectedValues }),
+ commitSelectedValues: () => ({ selectedValues: values.selectedValues, hasChanges: values.hasChanges }),
+ })),
+ reducers(({ props }) => ({
+ selectedValues: [
+ props.selectedValues,
+ {
+ setSelectedValues: (_, { selectedValues }) => selectedValues,
+ resetSelectedValues: (_, { selectedValues }) => selectedValues,
+ },
+ ],
+ hasChanges: [
+ false,
+ {
+ setSelectedValues: () => true,
+ resetSelectedValues: () => false,
+ commitSelectedValues: () => false,
+ },
+ ],
+ })),
+ listeners(({ props }) => ({
+ commitSelectedValues: ({ selectedValues, hasChanges }) => {
+ if (hasChanges) {
+ props.onChange(selectedValues)
+ }
+ },
+ })),
+ propsChanged(({ actions, props }, oldProps) => {
+ if (!equalSelectedValues(props.selectedValues, oldProps.selectedValues)) {
+ actions.resetSelectedValues(props.selectedValues)
+ }
+ }),
+ ])
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableModalLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableModalLogic.ts
index 210edc500ed5..f86cb2753f94 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableModalLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableModalLogic.ts
@@ -73,6 +73,9 @@ const getDefaultVariableForType = (variableType: VariableType): Variable => {
values: [],
default_value: '',
code_name: '',
+ is_multi: false,
+ values_query: null,
+ values_query_connection_id: null,
} as ListVariable
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableUtils.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableUtils.ts
new file mode 100644
index 000000000000..301a438e3d94
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableUtils.ts
@@ -0,0 +1,94 @@
+import { ListVariable } from '../../types'
+
+export type RelativeDateUnit = 'h' | 'd' | 'w' | 'm' | 'y'
+
+export interface RelativeDateValue {
+ amount: number
+ unit: RelativeDateUnit
+}
+
+export const coerceListVariableValue = (value: unknown): string | null => {
+ if (value == null) {
+ return null
+ }
+ if (typeof value === 'string') {
+ return value
+ }
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ return String(value)
+ }
+ if (typeof value === 'object' && !Array.isArray(value)) {
+ const record = value as Record<string, unknown>
+ for (const key of ['value', 'label']) {
+ const inner = record[key]
+ if (typeof inner === 'string') {
+ return inner
+ }
+ if (typeof inner === 'number' || typeof inner === 'boolean') {
+ return String(inner)
+ }
+ }
+ }
+ try {
+ return JSON.stringify(value) ?? null
+ } catch {
+ return String(value)
+ }
+}
+
+export const getListVariableValues = (variable: ListVariable): string[] =>
+ Array.isArray(variable.values)
+ ? variable.values.map(coerceListVariableValue).filter((value): value is string => value !== null)
+ : []
+
+export const getListVariableSelectedValues = (variable: ListVariable): string[] => {
+ const selectedValue = variable.value ?? variable.default_value
+ const rawValues = Array.isArray(selectedValue) ? selectedValue : [selectedValue]
+ const selectedValues = rawValues
+ .map(coerceListVariableValue)
+ .filter((value): value is string => value !== null && value !== '')
+
+ return variable.is_multi ? selectedValues : selectedValues.slice(0, 1)
+}
+
+export const normalizeRelativeDateAmount = (amount: unknown): number => {
+ const parsedAmount = Number(amount)
+ return Number.isFinite(parsedAmount) ? Math.max(0, Math.round(parsedAmount)) : 0
+}
+
+// Keep in sync with parseRelativeDateValue — the backend resolves a wider grammar
+// (see is_relative_date_value in posthog/hogql/variables.py), but values this UI
+// can't parse must not open the relative editor, which would rewrite them on edit.
+export const isRelativeDateValue = (value: string): boolean => /^-\d+[hdwmy]$/.test(value)
+
+export const parseRelativeDateValue = (value: string): RelativeDateValue | null => {
+ const match = value.match(/^-(\d+)([hdwmy])$/)
+ if (!match) {
+ return null
+ }
+
+ return {
+ amount: Number(match[1]),
+ unit: match[2] as RelativeDateUnit,
+ }
+}
+
+export const formatRelativeDateValue = (value: string): string => {
+ const parsedValue = parseRelativeDateValue(value)
+ if (!parsedValue) {
+ return value
+ }
+ if (parsedValue.amount === 0) {
+ return 'Now'
+ }
+
+ const unitLabels: Record<RelativeDateUnit, string> = {
+ h: 'hour',
+ d: 'day',
+ w: 'week',
+ m: 'month',
+ y: 'year',
+ }
+ const unit = unitLabels[parsedValue.unit]
+ return `${parsedValue.amount} ${unit}${parsedValue.amount === 1 ? '' : 's'} ago`
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableValuesLogic.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableValuesLogic.test.ts
new file mode 100644
index 000000000000..93683629aafa
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableValuesLogic.test.ts
@@ -0,0 +1,69 @@
+import { performQuery } from '~/queries/query'
+
+import { ListVariable } from '../../types'
+import { loadListVariableOptions, queryResultsToVariableOptions } from './variableValuesLogic'
+
+jest.mock('~/queries/query', () => ({
+ performQuery: jest.fn(),
+}))
+
+const queryVariable: ListVariable = {
+ id: 'variable-id',
+ name: 'Event names',
+ code_name: 'event_names',
+ type: 'List',
+ values: [],
+ default_value: [],
+ is_multi: true,
+ values_query: 'SELECT event, count() FROM events GROUP BY event',
+}
+
+describe('variableValuesLogic', () => {
+ it('uses unique scalar values from the first query result column', () => {
+ expect(
+ queryResultsToVariableOptions([
+ ['pageview', 10],
+ ['signup', 5],
+ ['pageview', 3],
+ [42, 1],
+ [null, 1],
+ [{ unsupported: true }, 1],
+ ])
+ ).toEqual([
+ { value: 'pageview', label: '10' },
+ { value: 'signup', label: '5' },
+ { value: '42', label: '1' },
+ ])
+ })
+
+ it('falls back to the value as label when the second column is not scalar', () => {
+ expect(queryResultsToVariableOptions([['pageview'], ['signup', { unsupported: true }]])).toEqual([
+ { value: 'pageview', label: 'pageview' },
+ { value: 'signup', label: 'signup' },
+ ])
+ })
+
+ it('runs the configured HogQL query to load options', async () => {
+ jest.mocked(performQuery).mockResolvedValue({ results: [['pageview'], ['signup']] })
+
+ await expect(loadListVariableOptions(queryVariable)).resolves.toEqual([
+ { value: 'pageview', label: 'pageview' },
+ { value: 'signup', label: 'signup' },
+ ])
+ expect(performQuery).toHaveBeenCalledWith({
+ kind: 'HogQLQuery',
+ query: queryVariable.values_query,
+ })
+ })
+
+ it('runs the query against the configured connection', async () => {
+ jest.mocked(performQuery).mockResolvedValue({ results: [['pageview']] })
+
+ await loadListVariableOptions({ ...queryVariable, values_query_connection_id: 'connection-uuid' })
+ expect(performQuery).toHaveBeenCalledWith({
+ kind: 'HogQLQuery',
+ query: queryVariable.values_query,
+ connectionId: 'connection-uuid',
+ })
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableValuesLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableValuesLogic.ts
new file mode 100644
index 000000000000..6ffbd87a502b
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableValuesLogic.ts
@@ -0,0 +1,148 @@
+import { LogicWrapper, MakeLogicType, afterMount, kea, key, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { performQuery } from '~/queries/query'
+import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
+
+import { ListVariable } from '../../types'
+import { getListVariableValues } from './variableUtils'
+
+export interface VariableValuesLogicProps {
+ variable: ListVariable
+ loadOnMount: boolean
+}
+
+export interface VariableOption {
+ value: string
+ label: string
+}
+
+// Identifies which (connection, query) pair a load ran against, so consumers can tell
+// whether the loaded options still match the variable being edited. Null means static options.
+export const getValuesQueryKey = (variable: ListVariable): string | null => {
+ const valuesQuery = variable.values_query?.trim()
+ if (!valuesQuery) {
+ return null
+ }
+ return `${variable.values_query_connection_id ?? ''}\n${valuesQuery}`
+}
+
+const isScalar = (value: unknown): value is string | number | boolean =>
+ ['string', 'number', 'boolean'].includes(typeof value)
+
+export const queryResultsToVariableOptions = (results: unknown): VariableOption[] => {
+ if (!Array.isArray(results)) {
+ return []
+ }
+
+ const options: VariableOption[] = []
+ const seenValues = new Set<string>()
+ for (const row of results) {
+ const rawValue = Array.isArray(row) ? row[0] : row
+ if (!isScalar(rawValue)) {
+ continue
+ }
+ const value = String(rawValue)
+ if (seenValues.has(value)) {
+ continue
+ }
+ seenValues.add(value)
+ const rawLabel = Array.isArray(row) ? row[1] : undefined
+ options.push({ value, label: isScalar(rawLabel) ? String(rawLabel) : value })
+ }
+
+ return options
+}
+
+export const getStaticVariableOptions = (variable: ListVariable): VariableOption[] =>
+ getListVariableValues(variable).map((value) => ({ value, label: value }))
+
+export const loadListVariableOptions = async (variable: ListVariable): Promise<VariableOption[]> => {
+ const valuesQuery = variable.values_query?.trim()
+ if (!valuesQuery) {
+ return getStaticVariableOptions(variable)
+ }
+
+ const response = await performQuery<HogQLQuery>({
+ kind: NodeKind.HogQLQuery,
+ query: valuesQuery,
+ ...(variable.values_query_connection_id ? { connectionId: variable.values_query_connection_id } : {}),
+ })
+
+ return queryResultsToVariableOptions(response.results).slice(0, 1000)
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface variableValuesLogicValues {
+ requestedValuesQueryKey: string | null
+ variableOptions: VariableOption[]
+ variableOptionsError: string | null
+ variableOptionsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface variableValuesLogicActions {
+ loadVariableOptions: (variable?: ListVariable) => ListVariable
+ loadVariableOptionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadVariableOptionsSuccess: (
+ variableOptions: VariableOption[],
+ payload?: ListVariable
+ ) => {
+ variableOptions: VariableOption[]
+ payload?: ListVariable
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface variableValuesLogicMeta {
+ key: string
+}
+
+export type variableValuesLogicType = MakeLogicType<
+ variableValuesLogicValues,
+ variableValuesLogicActions,
+ VariableValuesLogicProps,
+ variableValuesLogicMeta
+>
+
+export const variableValuesLogic: LogicWrapper<variableValuesLogicType> = kea<variableValuesLogicType>([
+ props({} as VariableValuesLogicProps),
+ key((props) => props.variable.id || 'new'),
+ path((key) => ['queries', 'nodes', 'DataVisualization', 'Variables', 'variableValuesLogic', key]),
+ loaders(({ props }) => ({
+ variableOptions: [
+ [] as VariableOption[],
+ {
+ loadVariableOptions: async (variable?: ListVariable) =>
+ loadListVariableOptions(variable ?? props.variable),
+ },
+ ],
+ })),
+ reducers(({ props }) => ({
+ requestedValuesQueryKey: [
+ null as string | null,
+ {
+ loadVariableOptions: (_, variable) => getValuesQueryKey(variable ?? props.variable),
+ },
+ ],
+ variableOptionsError: [
+ null as string | null,
+ {
+ loadVariableOptions: () => null,
+ loadVariableOptionsSuccess: () => null,
+ loadVariableOptionsFailure: (_, { error, errorObject }) => errorObject?.detail ?? error,
+ },
+ ],
+ })),
+ afterMount(({ actions, props }) => {
+ if (props.loadOnMount) {
+ actions.loadVariableOptions(props.variable)
+ }
+ }),
+])
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts
index 113e82b492f3..41d3820c6ffd 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts
@@ -40,7 +40,11 @@ export interface VariablesLogicProps {
onUpdate?: (query: DataVisualizationNode) => void
}
-const convertValueToCorrectType = (value: string, type: VariableType): number | string | boolean => {
+const convertValueToCorrectType = (value: unknown, type: VariableType): unknown => {
+ if (type === 'List' && Array.isArray(value)) {
+ return value.map(String)
+ }
+
if (type === 'Number') {
return Number(value)
}
@@ -49,7 +53,7 @@ const convertValueToCorrectType = (value: string, type: VariableType): number |
return value.toLowerCase() === 'true'
}
- return value
+ return typeof value === 'string' ? value : String(value ?? '')
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
diff --git a/frontend/src/queries/nodes/DataVisualization/types.ts b/frontend/src/queries/nodes/DataVisualization/types.ts
index f6dac8319c74..2e4200661716 100644
--- a/frontend/src/queries/nodes/DataVisualization/types.ts
+++ b/frontend/src/queries/nodes/DataVisualization/types.ts
@@ -82,6 +82,9 @@ interface VariableBase {
type: VariableType
value?: any
isNull?: boolean
+ is_multi?: boolean
+ values_query?: string | null
+ values_query_connection_id?: string | null
}
export interface StringVariable extends VariableBase {
@@ -102,8 +105,8 @@ export interface BooleanVariable extends VariableBase {
export interface ListVariable extends VariableBase {
type: 'List'
values: string[]
- default_value: string
- value?: string
+ default_value: string | string[]
+ value?: string | string[]
}
export interface DateVariable extends VariableBase {
diff --git a/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsx b/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsx
index 0f2ca6d54fc3..4a71ce94fa62 100644
--- a/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsx
+++ b/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsx
@@ -2,14 +2,7 @@ import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { IconCopy, IconInfo } from '@posthog/icons'
-import {
- LemonInput,
- LemonInputSelect,
- LemonSegmentedButton,
- LemonSelect,
- LemonSkeleton,
- LemonTable,
-} from '@posthog/lemon-ui'
+import { LemonInput, LemonSelect, LemonSkeleton, LemonTable } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -20,8 +13,8 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { getListVariableValues } from '~/queries/nodes/DataVisualization/Components/Variables/VariableFields'
-import { ListVariable, VariableType } from '~/queries/nodes/DataVisualization/types'
+import { VariableSpecificFields } from '~/queries/nodes/DataVisualization/Components/Variables/VariableForm'
+import { Variable, VariableType } from '~/queries/nodes/DataVisualization/types'
import { VARIABLE_TYPE_OPTIONS, formatVariableReference, getCodeName } from './constants'
import { VARIABLE_INSIGHT_COLUMNS } from './insightColumns'
@@ -39,86 +32,24 @@ export const scene: SceneExport<SqlVariableEditSceneLogicProps> = {
function VariableTypeFields(): JSX.Element {
const { variableType, variableForm } = useValues(sqlVariableEditSceneLogic)
+ const { setVariableFormValues } = useActions(sqlVariableEditSceneLogic)
+ const variable = {
+ id: '',
+ name: '',
+ code_name: '',
+ default_value: '',
+ ...variableForm,
+ type: variableType,
+ ...(variableType === 'List' && { values: 'values' in variableForm ? (variableForm.values ?? []) : [] }),
+ } as Variable
- if (variableType === 'String') {
- return (
- <LemonField name="default_value" label="Default value">
- <LemonInput placeholder="Enter default value" />
- </LemonField>
- )
- }
-
- if (variableType === 'Number') {
- return (
- <LemonField name="default_value" label="Default value">
- <LemonInput type="number" placeholder="Enter default value" />
- </LemonField>
- )
- }
-
- if (variableType === 'Boolean') {
- return (
- <LemonField name="default_value" label="Default value">
- {({ value, onChange }) => (
- <LemonSegmentedButton
- className="w-full"
- value={value ? 'true' : 'false'}
- onChange={(val) => onChange(val === 'true')}
- options={[
- { value: 'true', label: 'true' },
- { value: 'false', label: 'false' },
- ]}
- />
- )}
- </LemonField>
- )
- }
-
- if (variableType === 'List') {
- return (
- <>
- <LemonField name="values" label="Options">
- {({ value, onChange }) => (
- <LemonInputSelect
- value={value || []}
- onChange={onChange}
- placeholder="Add options..."
- mode="multiple"
- allowCustomValues={true}
- options={[]}
- sortable={true}
- />
- )}
- </LemonField>
- <LemonField name="default_value" label="Default value">
- {({ value, onChange }) => (
- <LemonSelect
- className="w-full"
- placeholder="Select default value"
- value={value}
- options={getListVariableValues(variableForm as ListVariable).map((n: string) => ({
- label: n,
- value: n,
- }))}
- onChange={(val) => onChange(val ?? '')}
- allowClear
- dropdownMaxContentWidth
- />
- )}
- </LemonField>
- </>
- )
- }
-
- if (variableType === 'Date') {
- return (
- <LemonField name="default_value" label="Default value (YYYY-MM-DD)">
- <LemonInput placeholder="e.g., 2024-01-15" />
- </LemonField>
- )
- }
-
- return <></>
+ return (
+ <VariableSpecificFields
+ variable={variable}
+ updateVariable={(updatedVariable) => setVariableFormValues(updatedVariable)}
+ onSave={() => {}}
+ />
+ )
}
export function SqlVariableEditScene(): JSX.Element {
diff --git a/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.ts b/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.ts
index 62675797f9af..5e936722bd3a 100644
--- a/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.ts
+++ b/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.ts
@@ -14,6 +14,7 @@ import {
coerceListVariableValue,
getListVariableValues,
} from '~/queries/nodes/DataVisualization/Components/Variables/VariableFields'
+import { getListVariableSelectedValues } from '~/queries/nodes/DataVisualization/Components/Variables/variableUtils'
import { ListVariable, Variable, VariableType } from '~/queries/nodes/DataVisualization/types'
import { QueryBasedInsightModel } from '~/types'
@@ -39,9 +40,18 @@ export const variableToFormValues = (variable: Variable): Partial<Variable> =>
name: variable.name,
type: variable.type,
default_value:
- variable.type === 'List' ? (coerceListVariableValue(variable.default_value) ?? '') : variable.default_value,
+ variable.type === 'List'
+ ? variable.is_multi
+ ? getListVariableSelectedValues({ ...variable, value: undefined })
+ : (coerceListVariableValue(variable.default_value) ?? '')
+ : variable.default_value,
code_name: variable.code_name,
- ...(variable.type === 'List' && { values: getListVariableValues(variable as ListVariable) }),
+ ...(variable.type === 'List' && {
+ values: getListVariableValues(variable as ListVariable),
+ is_multi: Boolean(variable.is_multi),
+ values_query: variable.values_query ?? null,
+ values_query_connection_id: variable.values_query_connection_id ?? null,
+ }),
}) as Partial<Variable>
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -303,17 +313,25 @@ export const sqlVariableEditSceneLogic = kea<sqlVariableEditSceneLogicType>([
const isList = variable.type === 'List'
const defaultValueForm = variableForm.default_value ?? ''
const defaultValueSaved = isList
- ? (coerceListVariableValue(variable.default_value) ?? '')
+ ? variable.is_multi
+ ? getListVariableSelectedValues({ ...(variable as ListVariable), value: undefined })
+ : (coerceListVariableValue(variable.default_value) ?? '')
: (variable.default_value ?? '')
const valuesForm = (variableForm as any).values ?? null
const valuesSaved = isList
? getListVariableValues(variable as ListVariable)
: ((variable as any).values ?? null)
+ const isMultiForm = isList ? Boolean(variableForm.is_multi) : false
+ const valuesQueryForm = isList ? (variableForm.values_query ?? null) : null
+ const valuesQueryConnectionForm = isList ? (variableForm.values_query_connection_id ?? null) : null
return (
(variableForm.name ?? '') !== (variable.name ?? '') ||
variableType !== variable.type ||
JSON.stringify(defaultValueForm) !== JSON.stringify(defaultValueSaved) ||
- JSON.stringify(valuesForm) !== JSON.stringify(valuesSaved)
+ JSON.stringify(valuesForm) !== JSON.stringify(valuesSaved) ||
+ isMultiForm !== Boolean(variable.is_multi) ||
+ valuesQueryForm !== (variable.values_query ?? null) ||
+ valuesQueryConnectionForm !== (variable.values_query_connection_id ?? null)
)
},
],
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryVariablesMenu.tsx b/frontend/src/scenes/data-warehouse/editor/QueryVariablesMenu.tsx
index 9725cd5a3072..1e0e5e5717d4 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryVariablesMenu.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryVariablesMenu.tsx
@@ -21,7 +21,7 @@ import { variableModalLogic } from '~/queries/nodes/DataVisualization/Components
import { VariableInput } from '~/queries/nodes/DataVisualization/Components/Variables/Variables'
import { variablesLogic } from '~/queries/nodes/DataVisualization/Components/Variables/variablesLogic'
import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
-import { Variable } from '~/queries/nodes/DataVisualization/types'
+import { Variable, VariableType } from '~/queries/nodes/DataVisualization/types'
import { sqlEditorLogic } from './sqlEditorLogic'
@@ -234,30 +234,18 @@ export function QueryVariablesMenu({ disabledReason }: QueryVariablesMenuProps):
sideIcon: <IconExternal />,
}
+ // The menu's visibility is controlled, so clicking a nested item only closes the
+ // submenu — close the whole menu explicitly before handing over to the modal.
+ const newVariableTypes: VariableType[] = ['String', 'Number', 'Boolean', 'List', 'Date']
const newVariableMenuItem: LemonMenuItem = {
label: 'New variable',
- items: [
- {
- label: 'String',
- onClick: () => openNewVariableModal('String'),
- },
- {
- label: 'Number',
- onClick: () => openNewVariableModal('Number'),
- },
- {
- label: 'Boolean',
- onClick: () => openNewVariableModal('Boolean'),
- },
- {
- label: 'List',
- onClick: () => openNewVariableModal('List'),
- },
- {
- label: 'Date',
- onClick: () => openNewVariableModal('Date'),
+ items: newVariableTypes.map((variableType) => ({
+ label: variableType,
+ onClick: () => {
+ closeMenu()
+ openNewVariableModal(variableType)
},
- ],
+ })),
}
const menuItems: LemonMenuItems = variablesLoading
diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
index b9693e543040..06976638289d 100644
--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
@@ -85,6 +85,14 @@ function getConnectionEngine(
return 'postgres'
}
+export function getConnectionOptionLabel(source: ExternalDataSourceConnectionOptionApi): string {
+ const engine = getConnectionEngine(source)
+ const isSynced = source.access_method === 'warehouse'
+ // Prefer the user-set description, then the prefix; fall back to the source type name (never the raw UUID).
+ const name = source.description || source.prefix || source.source_type || source.id
+ return `${name} (${ENGINE_LABELS[engine]}${isSynced ? ' · synced' : ''})`
+}
+
export function getConnectionSelectorValue(
connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,
connectionOptionsLoading: boolean,
@@ -251,19 +259,12 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([
): ConnectionSelectOptionGroup[] => {
const sourceOptions = connectionOptionsLoading
? [{ value: LOADING_CONNECTIONS, label: 'Loading...', disabled: true }]
- : (connectionOptions ?? []).map((source) => {
- const engine = getConnectionEngine(source)
- const isSynced = source.access_method === 'warehouse'
- // Prefer the user-set description, then the prefix; fall back to the source type name (never the raw UUID).
- const name = source.description || source.prefix || source.source_type || source.id
-
- return {
- value: source.id,
- label: `${name} (${ENGINE_LABELS[engine]}${isSynced ? ' · synced' : ''})`,
- iconSrc: ENGINE_ICONS[engine],
- managementUrl: urls.dataWarehouseSource(`managed-${source.id}`),
- }
- })
+ : (connectionOptions ?? []).map((source) => ({
+ value: source.id,
+ label: getConnectionOptionLabel(source),
+ iconSrc: ENGINE_ICONS[getConnectionEngine(source)],
+ managementUrl: urls.dataWarehouseSource(`managed-${source.id}`),
+ }))
// Driven by the backend direct-SQL capability surface so the menu never drifts from
// the engines we actually support (a new direct source shows up with no frontend change).
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index e732206bccf5..f584b847ab1f 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -313,7 +313,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -1706,7 +1709,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -2788,7 +2794,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -4747,7 +4756,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -5992,7 +6004,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -6611,7 +6626,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -7767,7 +7785,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -9065,7 +9086,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -9944,7 +9968,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -10919,7 +10946,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -11611,7 +11641,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -12588,7 +12621,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
@@ -13744,7 +13780,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index 9c4b9005c585..5c6d1ec35cf5 100644
--- a/posthog/hogql/test/test_query.py
+++ b/posthog/hogql/test/test_query.py
@@ -1732,6 +1732,61 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
"Variable variable_two is missing from query. Did you mean: variable_one?",
)
+ @parameterized.expand(
+ [
+ ("array_value", ["pageview", "signup"], False, ["pageview", "signup"]),
+ ("legacy_scalar_value", "pageview", False, ["pageview"]),
+ ("missing_value", None, False, []),
+ ("explicit_null", ["pageview"], True, []),
+ ]
+ )
+ def test_multiselect_list_variable_is_substituted_as_an_array(
+ self, _name: str, value: object | None, is_null: bool, expected: list[str]
+ ) -> None:
+ insight_variable = InsightVariable.objects.create(
+ team=self.team,
+ name="Event names",
+ code_name="event_names",
+ type=InsightVariable.Type.LIST,
+ is_multi=True,
+ )
+ variables = {
+ "event_names": HogQLVariable(
+ code_name="event_names",
+ value=value,
+ isNull=is_null,
+ variableId=str(insight_variable.id),
+ )
+ }
+
+ response = execute_hogql_query("SELECT {variables.event_names}", team=self.team, variables=variables)
+
+ self.assertEqual(response.results, [(expected,)])
+
+ @freeze_time("2026-08-06 12:00:00")
+ def test_relative_date_variable_is_resolved_when_the_query_runs(self):
+ insight_variable = InsightVariable.objects.create(
+ team=self.team,
+ name="Start date",
+ code_name="start_date",
+ type=InsightVariable.Type.DATE,
+ default_value="-7d",
+ )
+ variables = {
+ "start_date": HogQLVariable(
+ code_name="start_date",
+ variableId=str(insight_variable.id),
+ )
+ }
+
+ response = execute_hogql_query(
+ "SELECT toString({variables.start_date})",
+ team=self.team,
+ variables=variables,
+ )
+
+ self.assertEqual(response.results, [("2026-07-30 12:00:00.000000",)])
+
@pytest.mark.usefixtures("unittest_snapshot")
def test_hogql_query_filters(self):
with freeze_time("2020-01-10"):
diff --git a/posthog/hogql/variables.py b/posthog/hogql/variables.py
index 2ee3e17f2cf9..f76c23cec4e8 100644
--- a/posthog/hogql/variables.py
+++ b/posthog/hogql/variables.py
@@ -1,3 +1,4 @@
+import re
from difflib import get_close_matches
from typing import TypeVar
@@ -8,6 +9,7 @@ from posthog.hogql.errors import QueryError
from posthog.hogql.visitor import CloningVisitor
from posthog.models.team.team import Team
+from posthog.utils import relative_date_parse
from products.product_analytics.backend.models.insight_variable import InsightVariable
@@ -48,7 +50,10 @@ class ReplaceVariables(CloningVisitor):
if not matching_insight_variable:
raise QueryError(f"Variable {variable_code_name} does not exist")
+ variable_definition = matching_insight_variable[0]
if matching_variable.isNull:
+ if variable_definition.type == InsightVariable.Type.LIST and variable_definition.is_multi:
+ return ast.Array(exprs=[])
return ast.Constant(value=None)
value = (
@@ -57,6 +62,22 @@ class ReplaceVariables(CloningVisitor):
else matching_insight_variable[0].default_value
)
+ if variable_definition.type == InsightVariable.Type.LIST:
+ if variable_definition.is_multi:
+ # Saved insights keep the scalar value from before a variable was
+ # toggled to multi — wrap it so {variables.x} is always an array.
+ items = value if isinstance(value, list) else ([] if value is None else [value])
+ return ast.Array(exprs=[ast.Constant(value=item) for item in items])
+ if not variable_definition.is_multi and isinstance(value, list):
+ value = value[0] if value else None
+
+ if (
+ variable_definition.type == InsightVariable.Type.DATE
+ and isinstance(value, str)
+ and is_relative_date_value(value)
+ ):
+ value = relative_date_parse(value, self.team.timezone_info)
+
return ast.Constant(value=value)
return super().visit_placeholder(node)
@@ -73,3 +94,7 @@ class ReplaceVariables(CloningVisitor):
if not available_variables:
return []
return get_close_matches(variable_code_name, available_variables, n=3, cutoff=0.6)
+
+
+def is_relative_date_value(value: str) -> bool:
+ return re.fullmatch(r"-?\d*[hdwmqysHDWMQY](?:Start|End)?", value) is not None
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 5377867549da..59da81b7d6b0 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -469,6 +469,18 @@ export interface InsightVariableApi {
readonly code_name: string | null
/** Allowed values for List variables. Null for other variable types. */
values?: unknown
+ /** Whether a List variable accepts multiple selected values. */
+ is_multi?: boolean
+ /**
+ * HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.
+ * @nullable
+ */
+ values_query?: string | null
+ /**
+ * ID of the external data source connection values_query runs against. Null runs it against PostHog.
+ * @nullable
+ */
+ values_query_connection_id?: string | null
}
export interface PaginatedInsightVariableListApi {
@@ -512,6 +524,18 @@ export interface PatchedInsightVariableApi {
readonly code_name?: string | null
/** Allowed values for List variables. Null for other variable types. */
values?: unknown
+ /** Whether a List variable accepts multiple selected values. */
+ is_multi?: boolean
+ /**
+ * HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.
+ * @nullable
+ */
+ values_query?: string | null
+ /**
+ * ID of the external data source connection values_query runs against. Null runs it against PostHog.
+ * @nullable
+ */
+ values_query_connection_id?: string | null
}
export interface QueryTabStateApi {
diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.ts
index a7d75c0f8e56..a198e1463c58 100644
--- a/products/data_warehouse/frontend/generated/api.zod.ts
+++ b/products/data_warehouse/frontend/generated/api.zod.ts
@@ -49,6 +49,17 @@ export const InsightVariablesCreateBody = /* @__PURE__ */ zod.object({
),
default_value: zod.unknown().optional().describe('Default value used when a query references this variable.'),
values: zod.unknown().optional().describe('Allowed values for List variables. Null for other variable types.'),
+ is_multi: zod.boolean().optional().describe('Whether a List variable accepts multiple selected values.'),
+ values_query: zod
+ .string()
+ .nullish()
+ .describe(
+ 'HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.'
+ ),
+ values_query_connection_id: zod
+ .string()
+ .nullish()
+ .describe('ID of the external data source connection values_query runs against. Null runs it against PostHog.'),
})
export const insightVariablesUpdateBodyNameMax = 400
@@ -65,6 +76,17 @@ export const InsightVariablesUpdateBody = /* @__PURE__ */ zod.object({
),
default_value: zod.unknown().optional().describe('Default value used when a query references this variable.'),
values: zod.unknown().optional().describe('Allowed values for List variables. Null for other variable types.'),
+ is_multi: zod.boolean().optional().describe('Whether a List variable accepts multiple selected values.'),
+ values_query: zod
+ .string()
+ .nullish()
+ .describe(
+ 'HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.'
+ ),
+ values_query_connection_id: zod
+ .string()
+ .nullish()
+ .describe('ID of the external data source connection values_query runs against. Null runs it against PostHog.'),
})
export const insightVariablesPartialUpdateBodyNameMax = 400
@@ -86,6 +108,17 @@ export const InsightVariablesPartialUpdateBody = /* @__PURE__ */ zod.object({
),
default_value: zod.unknown().optional().describe('Default value used when a query references this variable.'),
values: zod.unknown().optional().describe('Allowed values for List variables. Null for other variable types.'),
+ is_multi: zod.boolean().optional().describe('Whether a List variable accepts multiple selected values.'),
+ values_query: zod
+ .string()
+ .nullish()
+ .describe(
+ 'HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.'
+ ),
+ values_query_connection_id: zod
+ .string()
+ .nullish()
+ .describe('ID of the external data source connection values_query runs against. Null runs it against PostHog.'),
})
/**
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-variables.md b/products/posthog_ai/skills/querying-posthog-data/references/models-variables.md
index a0c34d2db69b..998d6b35e01d 100644
--- a/products/posthog_ai/skills/querying-posthog-data/references/models-variables.md
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-variables.md
@@ -13,6 +13,9 @@ Column | Type | Description
`type` | varchar(128) | `String`, `Number`, `Boolean`, `List`, or `Date`
`default_value` | jsonb | Default value
`values` | jsonb | Available values (List type only)
+`is_multi` | boolean | Whether a List variable accepts multiple selected values
+`values_query` | text | HogQL query whose first result column supplies List options
+`values_query_connection_id` | text | External data source connection `values_query` runs against (null for PostHog)
### Types
@@ -20,8 +23,8 @@ Type | Example `default_value`
`String` | `"example"`
`Number` | `42`
`Boolean` | `true`
-`List` | `["$pageview", "$autocapture"]`
-`Date` | `"2024-01-01"`
+`List` | `"$pageview"` or `["$pageview", "$autocapture"]` when `is_multi` is enabled
+`Date` | `"2024-01-01"` or a rolling value such as `"-7d"`
### Usage
@@ -34,8 +37,15 @@ WHERE (coalesce({variables.org}, '') = '' OR properties.org = {variables.org})
-- Optional nullable (null check)
WHERE ({variables.browser} IS NULL OR properties.$browser = {variables.browser})
+
+-- Multiselect List variable
+WHERE event IN {variables.event_names}
```
+List options can be entered manually or loaded from a HogQL query. For query-backed options, the first result column becomes the option values, and an optional second column supplies their display labels. Queries without a `LIMIT` return at most 100 rows, and the UI keeps at most 1000 options. The query can run against an external data source connection via `values_query_connection_id`.
+
+Relative Date defaults resolve each time a query runs. For example, `-7d` means seven days before the current time.
+
### code_name Generation
Auto-generated from `name`: strips non-alphanumeric characters (except spaces/underscores), replaces spaces with underscores, lowercases. Example: `"Event Names"` -> `"event_names"`
diff --git a/products/product_analytics/backend/api/insight_variable.py b/products/product_analytics/backend/api/insight_variable.py
index cc09562bd188..f405156dc10b 100644
--- a/products/product_analytics/backend/api/insight_variable.py
+++ b/products/product_analytics/backend/api/insight_variable.py
@@ -47,7 +47,19 @@ class InsightVariableSerializer(serializers.ModelSerializer):
class Meta:
model = InsightVariable
- fields = ["id", "name", "type", "default_value", "created_by", "created_at", "code_name", "values"]
+ fields = [
+ "id",
+ "name",
+ "type",
+ "default_value",
+ "created_by",
+ "created_at",
+ "code_name",
+ "values",
+ "is_multi",
+ "values_query",
+ "values_query_connection_id",
+ ]
read_only_fields = ["id", "code_name", "created_by", "created_at"]
extra_kwargs = {
@@ -61,20 +73,53 @@ class InsightVariableSerializer(serializers.ModelSerializer):
"help_text": "Generated code-safe name used in HogQL as {variables.code_name}. Derived from name."
},
"values": {"help_text": "Allowed values for List variables. Null for other variable types."},
+ "is_multi": {"help_text": "Whether a List variable accepts multiple selected values."},
+ "values_query": {
+ "help_text": "HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels."
+ },
+ "values_query_connection_id": {
+ "help_text": "ID of the external data source connection values_query runs against. Null runs it against PostHog."
+ },
}
def validate(self, attrs):
variable_type = attrs.get("type", getattr(self.instance, "type", None))
if variable_type == InsightVariable.Type.LIST:
+ is_multi = attrs.get("is_multi", getattr(self.instance, "is_multi", False))
+ if "is_multi" in attrs and "default_value" not in attrs and self.instance is not None:
+ attrs["default_value"] = self.instance.default_value
+ elif is_multi and "default_value" not in attrs and self.instance is None:
+ attrs["default_value"] = []
# Only validate `values` when the payload provides it — instance data may hold
# legacy shapes that shouldn't block unrelated updates (reads normalize them).
if "values" in attrs:
values = attrs["values"]
attrs["values"] = self._coerce_list_values(values) if isinstance(values, list) else []
- # `default_value` is a single option; coerce leniently so a legacy shape or a
- # round-tripped read can't be stored as non-string (the UI treats it as text).
+ # A blank query means "not query-backed" — store null so the UI falls back to static options.
+ if isinstance(attrs.get("values_query"), str) and not attrs["values_query"].strip():
+ attrs["values_query"] = None
+ effective_values_query = (
+ attrs["values_query"] if "values_query" in attrs else getattr(self.instance, "values_query", None)
+ )
+ if effective_values_query is None:
+ attrs["values_query_connection_id"] = None
if "default_value" in attrs:
- attrs["default_value"] = _coerce_list_value_lenient(attrs["default_value"]) or ""
+ default_value = attrs["default_value"]
+ if is_multi:
+ raw_default_values = default_value if isinstance(default_value, list) else [default_value]
+ attrs["default_value"] = [
+ value
+ for raw_value in raw_default_values
+ if (value := _coerce_list_value_lenient(raw_value)) is not None
+ ]
+ elif isinstance(default_value, list):
+ attrs["default_value"] = _coerce_list_value_lenient(default_value[0]) if default_value else ""
+ else:
+ attrs["default_value"] = _coerce_list_value_lenient(default_value) or ""
+ else:
+ attrs["is_multi"] = False
+ attrs["values_query"] = None
+ attrs["values_query_connection_id"] = None
return attrs
@@ -107,7 +152,16 @@ class InsightVariableSerializer(serializers.ModelSerializer):
if isinstance(raw_values, list)
else []
)
- data["default_value"] = _coerce_list_value_lenient(data.get("default_value"))
+ raw_default_value = data.get("default_value")
+ if instance.is_multi:
+ raw_default_values = raw_default_value if isinstance(raw_default_value, list) else [raw_default_value]
+ data["default_value"] = [
+ value
+ for raw_value in raw_default_values
+ if (value := _coerce_list_value_lenient(raw_value)) is not None
+ ]
+ else:
+ data["default_value"] = _coerce_list_value_lenient(raw_default_value)
return data
def create(self, validated_data):
diff --git a/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr b/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr
index 5cf25bd00fff..0828eb326cdb 100644
--- a/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr
@@ -589,7 +589,10 @@
"posthog_insightvariable"."code_name",
"posthog_insightvariable"."type",
"posthog_insightvariable"."default_value",
- "posthog_insightvariable"."values"
+ "posthog_insightvariable"."values",
+ "posthog_insightvariable"."is_multi",
+ "posthog_insightvariable"."values_query",
+ "posthog_insightvariable"."values_query_connection_id"
FROM "posthog_insightvariable"
WHERE "posthog_insightvariable"."team_id" = 99999
'''
diff --git a/products/product_analytics/backend/api/test/test_insight_variable.py b/products/product_analytics/backend/api/test/test_insight_variable.py
index 6aafbea38378..7c69a3c111f8 100644
--- a/products/product_analytics/backend/api/test/test_insight_variable.py
+++ b/products/product_analytics/backend/api/test/test_insight_variable.py
@@ -9,7 +9,11 @@ from rest_framework.exceptions import PermissionDenied
from posthog.auth import SharingAccessTokenAuthentication
-from products.product_analytics.backend.api.insight_variable import InsightVariableViewSet, map_stale_to_latest
+from products.product_analytics.backend.api.insight_variable import (
+ InsightVariableSerializer,
+ InsightVariableViewSet,
+ map_stale_to_latest,
+)
from products.product_analytics.backend.models.insight_variable import InsightVariable
@@ -61,6 +65,93 @@ class TestInsightVariable(APIBaseTest):
assert response.status_code == 201
assert response.json()["values"] == []
+ def test_create_query_backed_multiselect_list_variable(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/insight_variables/",
+ data={
+ "name": "Event names",
+ "type": "List",
+ "values": [],
+ "default_value": ["pageview", "signup"],
+ "is_multi": True,
+ "values_query": "SELECT DISTINCT event FROM events LIMIT 100",
+ "values_query_connection_id": "connection-uuid",
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == 201
+ assert response.json()["default_value"] == ["pageview", "signup"]
+ assert response.json()["is_multi"] is True
+ assert response.json()["values_query"] == "SELECT DISTINCT event FROM events LIMIT 100"
+ assert response.json()["values_query_connection_id"] == "connection-uuid"
+
+ variable = InsightVariable.objects.get(team_id=self.team.pk)
+ assert variable.default_value == ["pageview", "signup"]
+ assert variable.is_multi is True
+ assert variable.values_query == "SELECT DISTINCT event FROM events LIMIT 100"
+ assert variable.values_query_connection_id == "connection-uuid"
+
+ def test_blank_values_query_is_stored_as_null(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/insight_variables/",
+ data={
+ "name": "Event name",
+ "type": "List",
+ "values": ["pageview"],
+ "values_query": " ",
+ "values_query_connection_id": "connection-uuid",
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == 201
+ assert response.json()["values_query"] is None
+ assert response.json()["values_query_connection_id"] is None
+
+ def test_switching_to_static_options_clears_the_connection(self):
+ variable = InsightVariable.objects.create(
+ team=self.team,
+ name="Event name",
+ type="List",
+ code_name="event_name",
+ values=[],
+ values_query="SELECT event FROM events",
+ values_query_connection_id="connection-uuid",
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/insight_variables/{variable.id}/",
+ data={"values_query": None},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ variable.refresh_from_db()
+ assert variable.values_query is None
+ assert variable.values_query_connection_id is None
+
+ def test_enabling_multiselect_normalizes_existing_default(self):
+ variable = InsightVariable.objects.create(
+ team=self.team,
+ name="Event name",
+ type="List",
+ code_name="event_name",
+ values=["pageview", "signup"],
+ default_value="pageview",
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/insight_variables/{variable.id}/",
+ data={"is_multi": True},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ assert response.json()["default_value"] == ["pageview"]
+ variable.refresh_from_db()
+ assert variable.default_value == ["pageview"]
+
def test_insight_variable_limit(self):
# default list call should return up to 500 variables
response = self.client.get(f"/api/environments/{self.team.pk}/insight_variables/")
@@ -237,6 +328,14 @@ class TestInsightVariable(APIBaseTest):
assert response.json()["values"] == []
+class TestInsightVariableSerializer(TestCase):
+ def test_multiselect_create_without_default_uses_empty_list(self) -> None:
+ serializer = InsightVariableSerializer(data={"name": "Event names", "type": "List", "is_multi": True})
+
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["default_value"] == []
+
+
class TestMapStaleToLatest(TestCase):
def _make_variable(self, code_name: str) -> InsightVariable:
var = MagicMock(spec=InsightVariable)
diff --git a/products/product_analytics/backend/migrations/0005_insightvariable_is_multi_and_more.py b/products/product_analytics/backend/migrations/0005_insightvariable_is_multi_and_more.py
new file mode 100644
index 000000000000..5152e6a484c9
--- /dev/null
+++ b/products/product_analytics/backend/migrations/0005_insightvariable_is_multi_and_more.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.17 on 2026-08-06 12:40
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product_analytics", "0004_delete_revenue_analytics_insights"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="insightvariable",
+ name="is_multi",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ migrations.AddField(
+ model_name="insightvariable",
+ name="values_query",
+ field=models.TextField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/product_analytics/backend/migrations/0006_insightvariable_values_query_connection_id.py b/products/product_analytics/backend/migrations/0006_insightvariable_values_query_connection_id.py
new file mode 100644
index 000000000000..0e43f0aa4ac6
--- /dev/null
+++ b/products/product_analytics/backend/migrations/0006_insightvariable_values_query_connection_id.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-08-07 11:55
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product_analytics", "0005_insightvariable_is_multi_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="insightvariable",
+ name="values_query_connection_id",
+ field=models.TextField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/product_analytics/backend/migrations/max_migration.txt b/products/product_analytics/backend/migrations/max_migration.txt
index b759d38d6aa7..e583ff417d8a 100644
--- a/products/product_analytics/backend/migrations/max_migration.txt
+++ b/products/product_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_delete_revenue_analytics_insights
+0006_insightvariable_values_query_connection_id
diff --git a/products/product_analytics/backend/models/insight_variable.py b/products/product_analytics/backend/models/insight_variable.py
index bc75b9828c4e..925998a699d6 100644
--- a/products/product_analytics/backend/models/insight_variable.py
+++ b/products/product_analytics/backend/models/insight_variable.py
@@ -17,6 +17,9 @@ class InsightVariable(UUIDTModel, RootTeamMixin, CreatedMetaFields, UpdatedMetaF
type = models.CharField(max_length=128, choices=Type)
default_value = models.JSONField(null=True, blank=True)
values = models.JSONField(null=True, blank=True)
+ is_multi = models.BooleanField(default=False, db_default=False)
+ values_query = models.TextField(null=True, blank=True)
+ values_query_connection_id = models.TextField(null=True, blank=True)
__repr__ = sane_repr("id")
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2754bfbf41b6..2ce07cccaf43 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39483,6 +39483,18 @@ export namespace Schemas {
readonly code_name: string | null;
/** Allowed values for List variables. Null for other variable types. */
values?: unknown;
+ /** Whether a List variable accepts multiple selected values. */
+ is_multi?: boolean;
+ /**
+ * HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.
+ * @nullable
+ */
+ values_query?: string | null;
+ /**
+ * ID of the external data source connection values_query runs against. Null runs it against PostHog.
+ * @nullable
+ */
+ values_query_connection_id?: string | null;
}
export interface InsightViewedRequest {
@@ -54792,6 +54804,18 @@ export namespace Schemas {
readonly code_name?: string | null;
/** Allowed values for List variables. Null for other variable types. */
values?: unknown;
+ /** Whether a List variable accepts multiple selected values. */
+ is_multi?: boolean;
+ /**
+ * HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.
+ * @nullable
+ */
+ values_query?: string | null;
+ /**
+ * ID of the external data source connection values_query runs against. Null runs it against PostHog.
+ * @nullable
+ */
+ values_query_connection_id?: string | null;
}
/**
diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.ts
index b5a0ec96c1af..cb0834896de3 100644
--- a/services/mcp/src/generated/data_warehouse/api.ts
+++ b/services/mcp/src/generated/data_warehouse/api.ts
@@ -30,6 +30,17 @@ export const InsightVariablesCreateBody = /* @__PURE__ */ zod.object({
),
default_value: zod.unknown().optional().describe('Default value used when a query references this variable.'),
values: zod.unknown().optional().describe('Allowed values for List variables. Null for other variable types.'),
+ is_multi: zod.boolean().optional().describe('Whether a List variable accepts multiple selected values.'),
+ values_query: zod
+ .string()
+ .nullish()
+ .describe(
+ 'HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.'
+ ),
+ values_query_connection_id: zod
+ .string()
+ .nullish()
+ .describe('ID of the external data source connection values_query runs against. Null runs it against PostHog.'),
})
export const InsightVariablesPartialUpdateParams = /* @__PURE__ */ zod.object({
@@ -60,6 +71,17 @@ export const InsightVariablesPartialUpdateBody = /* @__PURE__ */ zod.object({
),
default_value: zod.unknown().optional().describe('Default value used when a query references this variable.'),
values: zod.unknown().optional().describe('Allowed values for List variables. Null for other variable types.'),
+ is_multi: zod.boolean().optional().describe('Whether a List variable accepts multiple selected values.'),
+ values_query: zod
+ .string()
+ .nullish()
+ .describe(
+ 'HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels.'
+ ),
+ values_query_connection_id: zod
+ .string()
+ .nullish()
+ .describe('ID of the external data source connection values_query runs against. Null runs it against PostHog.'),
})
export const InsightVariablesDestroyParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.ts
index 44f1f7f7c6cc..510e1717c52a 100644
--- a/services/mcp/src/tools/generated/data_warehouse.ts
+++ b/services/mcp/src/tools/generated/data_warehouse.ts
@@ -107,6 +107,15 @@ const sqlVariablesCreate = (): ToolBase<typeof SqlVariablesCreateSchema, Schemas
if (params.values !== undefined) {
body['values'] = params.values
}
+ if (params.is_multi !== undefined) {
+ body['is_multi'] = params.is_multi
+ }
+ if (params.values_query !== undefined) {
+ body['values_query'] = params.values_query
+ }
+ if (params.values_query_connection_id !== undefined) {
+ body['values_query_connection_id'] = params.values_query_connection_id
+ }
const result = await context.api.request<Schemas.InsightVariable>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/insight_variables/`,
@@ -153,6 +162,15 @@ const sqlVariablesUpdate = (): ToolBase<typeof SqlVariablesUpdateSchema, Schemas
if (params.values !== undefined) {
body['values'] = params.values
}
+ if (params.is_multi !== undefined) {
+ body['is_multi'] = params.is_multi
+ }
+ if (params.values_query !== undefined) {
+ body['values_query'] = params.values_query
+ }
+ if (params.values_query_connection_id !== undefined) {
+ body['values_query_connection_id'] = params.values_query_connection_id
+ }
const result = await context.api.request<Schemas.InsightVariable>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/insight_variables/${encodeURIComponent(String(params.id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-create.json
index 0e9ab82a9a94..e049aa8fb875 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-create.json
@@ -4,6 +4,10 @@
"default_value": {
"description": "Default value used when a query references this variable."
},
+ "is_multi": {
+ "description": "Whether a List variable accepts multiple selected values.",
+ "type": "boolean"
+ },
"name": {
"description": "Human-readable name for the SQL variable.",
"maxLength": 400,
@@ -16,6 +20,28 @@
},
"values": {
"description": "Allowed values for List variables. Null for other variable types."
+ },
+ "values_query": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels."
+ },
+ "values_query_connection_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "ID of the external data source connection values_query runs against. Null runs it against PostHog."
}
},
"required": ["name", "type"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-update.json
index 08536eea8a49..8448e05960b8 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/sql-variables-update.json
@@ -8,6 +8,10 @@
"description": "A UUID string identifying this insight variable.",
"type": "string"
},
+ "is_multi": {
+ "description": "Whether a List variable accepts multiple selected values.",
+ "type": "boolean"
+ },
"name": {
"description": "Human-readable name for the SQL variable.",
"maxLength": 400,
@@ -20,6 +24,28 @@
},
"values": {
"description": "Allowed values for List variables. Null for other variable types."
+ },
+ "values_query": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "HogQL query whose first result column supplies the allowed values for a List variable. An optional second column supplies display labels."
+ },
+ "values_query_connection_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "ID of the external data source connection values_query runs against. Null runs it against PostHog."
}
},
"required": ["id"],