Skip to content

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

feat(bi): reuse worksheet-local hogql expressions (#115512)

Marius Andrab424e3d3498b
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 751883d4bf32..4b7ae19678d7 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -82,14 +82,9 @@ Click a bar, line point, table cell, or pivot cell to explore its source rows. *
**Compare previous period** turns date comparison on or off in one click. The adjacent comparison picker still supports custom offsets. Select a bounded date range before enabling comparison.
-With `SQL_EDITOR_BI_MODE` enabled, open **Business intelligence**, select a table and choose **Add calculated measure** in the data pane.
-Enter a name and an aggregate SQL formula, such as `sum(revenue) / nullIf(count(DISTINCT user_id), 0)` for average revenue per user.
-Use field names from the selected table. Filters apply before the formula runs for each group on the worksheet.
-
-The measure appears on Rows. Its menu lets you edit the name and formula, sort by the measure, or remove it.
-Cancel discards the draft. Names and formulas persist with the worksheet's BI configuration; measures are not shared across worksheets.
-Calculated measures cannot become dimensions or row filters.
-If a measure name conflicts with a field or another result column, the generated query adds a numeric suffix to its column name. The worksheet keeps the name you entered on the measure pill and sort menu.
+With `SQL_EDITOR_BI_MODE` enabled, choose **Add calculated field** in the data pane. Select a row-level dimension or an aggregate measure, then enter a name and a plain HogQL expression using fields from the selected table. Dimensions can use expressions such as `coalesce(properties.plan, 'Unknown')`; measures can use `sum(revenue) / nullIf(count(DISTINCT user_id), 0)`.
+
+Calculated fields appear in Dimensions or Measures with a ƒ indicator. Drag or double-click them to reuse the definition. Editing a definition updates its name and expression on every shelf, including duplicated uses; date granularities and measure display settings remain independent. A field's role cannot change after creation. **Delete field and all uses** removes the local definition and its shelf/filter uses; Undo restores them. Clear sheet retains the definitions. Save, reload, and Save a copy preserve them inside the worksheet, without creating source-table or project-wide fields.
## Filters in BI mode
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b9caeba8a34d..26c17e389ad9 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9995,9 +9995,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
hash: v1.k794b7964.e1cc84afbf9401c2e88538e5f6afb9056e0d9693be4a3c211a892d6bd70c77a1.NymFaclvHrxgQW2VYDpcYNk4WJFiZKbYAVIocq0enEw
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.2fa8b4975109cb718436d4737fd9ca2f5425bf1ccb1883f414846691626e3310.nAj2tzBfZHRkob6UIbR4XYiGqKIqlu3vP7OBn3hRZlo
+ hash: v1.k794b7964.091d05fb9c40b05c4aad2ab106fbb67512f604e692a2ca858dfa0d0c00601198.kP7jRmsrb5_JfzEZy9Gw1f_p7KsViCRG_AbDGmOR6PY
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.bcbcef0fe7f0a57f26f7520fadc60b3abf49e5d0644add03a1887059cd9641c9.0UkQ8L585g-o5HU47TayuhlTRkRmr_MDTZdptAOJOUA
+ hash: v1.k794b7964.d3a14111f6d0c02cf2884c6c09a88f73e34cd69a3adb67d67afa5e270ca65e95.olfq2wvtKhq3FiRHdlLiTClMFJNRcus3M3nbn8LyEiE
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.06df092616d217a4ebdaf0f5f35015c05fe63f5bc1e9b9c39dcdf6594293c0e3.D8zEjaefT5868HRYC8F6GkfsuMMlcxSxekM5z-VoXyM
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 1deb3fb8c278..49814f8ea18c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6287,6 +6287,9 @@
"localDefinition": {
"$ref": "#/definitions/BILocalFieldDefinition"
},
+ "localFieldId": {
+ "type": "string"
+ },
"name": {
"type": "string"
},
@@ -6350,6 +6353,23 @@
},
"BILocalFieldDefinition": {
"anyOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "aggregate": {
+ "type": "boolean"
+ },
+ "expression": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "expression",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "expression", "aggregate"],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index 815f84d00436..e0a51c9ca4ed 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -64,9 +64,11 @@ export interface BIField {
dateBucket?: BIDateBucket
datePart?: 'month' | 'quarter' | 'day_of_week'
localDefinition?: BILocalFieldDefinition
+ localFieldId?: string
}
export type BILocalFieldDefinition =
+ | { kind: 'expression'; expression: string; aggregate: boolean }
| { kind: 'groups'; expression: string; groups: BICategoryGroup[]; other: string }
| { kind: 'bins'; expression: string; width: number; origin: number }
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 13122ef25ffe..7548cb7cccf9 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -616,10 +616,12 @@ export const BICalculatedMeasureEditor: Story = {
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
- const addMeasure = await canvas.findByText('Add calculated measure', {}, { timeout: 15000 })
- await waitFor(() => expect(addMeasure.closest('button')).toBeEnabled())
+ const addMeasure = await canvas.findByRole('button', { name: 'Add calculated field' }, { timeout: 15000 })
+ await waitFor(() => expect(addMeasure).toBeEnabled())
await userEvent.click(addMeasure)
const modal = within(canvasElement.ownerDocument.body)
+ await userEvent.click(await modal.findByLabelText('Calculated field role'))
+ await userEvent.click(await modal.findByText('Measure · aggregate each group'))
await userEvent.type(await modal.findByLabelText('Name'), 'ARPU')
},
}
diff --git a/posthog/schema.py b/posthog/schema.py
index 92e8fd545fe2..0bc74b652828 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -990,6 +990,15 @@ class BIDataSource(BaseModel):
class BILocalFieldDefinition1(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ aggregate: bool
+ expression: str
+ kind: Literal["expression"] = "expression"
+
+
+class BILocalFieldDefinition2(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -999,7 +1008,7 @@ class BILocalFieldDefinition1(BaseModel):
other: str
-class BILocalFieldDefinition2(BaseModel):
+class BILocalFieldDefinition3(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -5115,7 +5124,8 @@ class BIField(BaseModel):
datePart: DatePart | None = None
expression: str
id: str
- localDefinition: BILocalFieldDefinition1 | BILocalFieldDefinition2 | None = None
+ localDefinition: BILocalFieldDefinition1 | BILocalFieldDefinition2 | BILocalFieldDefinition3 | None = None
+ localFieldId: str | None = None
name: str
source: BIDataSource
type: DatabaseSerializedFieldType
diff --git a/products/business_intelligence/frontend/BICalculatedMeasureModal.tsx b/products/business_intelligence/frontend/BICalculatedMeasureModal.tsx
index d1b59cd4ea03..88c079bd20c2 100644
--- a/products/business_intelligence/frontend/BICalculatedMeasureModal.tsx
+++ b/products/business_intelligence/frontend/BICalculatedMeasureModal.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonInput, LemonLabel, LemonModal } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonLabel, LemonModal, LemonSelect } from '@posthog/lemon-ui'
import { CodeEditorInline } from 'lib/monaco/CodeEditorInline'
@@ -10,7 +10,7 @@ import { escapeDottedHogQLIdentifier } from '~/queries/utils'
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
export function BICalculatedMeasureModal(): JSX.Element | null {
- const { calculatedMeasureDraft: draft, config } = useValues(biEditorLogic)
+ const { calculatedMeasureDraft: draft, calculatedFieldError, config } = useValues(biEditorLogic)
const { setCalculatedMeasureDraft, saveCalculatedMeasure } = useActions(biEditorLogic)
if (!draft || !config.source) {
@@ -20,7 +20,7 @@ export function BICalculatedMeasureModal(): JSX.Element | null {
return (
<LemonModal
isOpen
- title={draft.index === null ? 'Add calculated measure' : 'Edit calculated measure'}
+ title={draft.index === null && !draft.fieldId ? 'Add calculated field' : 'Edit calculated field'}
onClose={() => setCalculatedMeasureDraft(null)}
width="36rem"
data-attr="bi-calculated-measure-modal"
@@ -32,40 +32,69 @@ export function BICalculatedMeasureModal(): JSX.Element | null {
<LemonButton
type="primary"
onClick={saveCalculatedMeasure}
- disabledReason={
- !draft.name.trim()
- ? 'Enter a name for this measure'
- : !draft.expression.trim()
- ? 'Enter a formula for this measure'
- : undefined
- }
+ disabledReason={calculatedFieldError}
data-attr="bi-calculated-measure-save"
>
- {draft.index === null ? 'Add measure' : 'Save measure'}
+ {draft.index === null && !draft.fieldId ? 'Add field' : 'Save field'}
</LemonButton>
</>
}
>
<div className="flex flex-col gap-4">
+ <p className="m-0 text-secondary">
+ This field stays in this worksheet. Editing it updates every use here. It does not add a field to
+ the source table.
+ </p>
+ <div className="flex flex-wrap gap-3">
+ <LemonSelect
+ aria-label="Calculated field role"
+ value={draft.kind ?? 'measure'}
+ options={[
+ { value: 'dimension', label: 'Dimension · one value per row' },
+ { value: 'measure', label: 'Measure · aggregate each group' },
+ ]}
+ onChange={(kind) =>
+ setCalculatedMeasureDraft({ ...draft, kind, type: kind === 'measure' ? 'float' : 'string' })
+ }
+ disabledReason={
+ draft.fieldId || draft.index !== null ? 'Create a new field to change its role' : undefined
+ }
+ />
+ {draft.kind === 'dimension' && (
+ <LemonSelect
+ aria-label="Calculated field type"
+ value={draft.type ?? 'string'}
+ options={[
+ { value: 'string', label: 'Text' },
+ { value: 'integer', label: 'Integer' },
+ { value: 'float', label: 'Number' },
+ { value: 'boolean', label: 'Boolean' },
+ { value: 'date', label: 'Date' },
+ { value: 'datetime', label: 'Date and time' },
+ ]}
+ onChange={(type) => setCalculatedMeasureDraft({ ...draft, type })}
+ />
+ )}
+ </div>
<div className="flex flex-col gap-1">
<LemonLabel htmlFor="bi-calculated-measure-name">Name</LemonLabel>
<LemonInput
id="bi-calculated-measure-name"
value={draft.name}
onChange={(name) => setCalculatedMeasureDraft({ ...draft, name })}
- placeholder="For example, ARPU"
+ placeholder={draft.kind === 'dimension' ? 'For example, Plan' : 'For example, ARPU'}
autoFocus
data-attr="bi-calculated-measure-name"
/>
</div>
<div className="flex flex-col gap-2">
- <LemonLabel>Formula</LemonLabel>
+ <LemonLabel>HogQL expression</LemonLabel>
<CodeEditorInline
value={draft.expression}
onChange={(expression) => setCalculatedMeasureDraft({ ...draft, expression: expression ?? '' })}
language="hogQLExpr"
minHeight="100px"
- options={{ ariaLabel: 'Calculated measure formula' }}
+ options={{ ariaLabel: 'Calculated field expression' }}
sourceQuery={{
kind: NodeKind.HogQLQuery,
query: `SELECT * FROM ${escapeDottedHogQLIdentifier(config.source.table)}`,
@@ -75,16 +104,19 @@ export function BICalculatedMeasureModal(): JSX.Element | null {
data-attr="bi-calculated-measure-formula"
/>
<p className="m-0 text-xs text-secondary">
- Use SQL aggregate functions such as sum, count, and avg. The formula is calculated for each
- group on your worksheet, after filters are applied.
+ {draft.kind === 'dimension'
+ ? "Use a row expression, such as coalesce(properties.plan, 'Unknown'). Refer to fields from the selected table using HogQL."
+ : 'Use aggregate functions such as sum, count, and avg. The expression runs for each group after row filters.'}
</p>
- <div className="rounded border bg-surface-primary p-2 text-xs">
- <div className="mb-1 font-semibold">Average revenue per user</div>
- <code className="break-words">sum(revenue) / nullIf(count(DISTINCT user_id), 0)</code>
- <p className="mb-0 mt-1 text-secondary">
- Replace revenue and user_id with your fields. nullIf avoids division by zero.
- </p>
- </div>
+ {draft.kind !== 'dimension' && (
+ <div className="rounded border bg-surface-primary p-2 text-xs">
+ <div className="mb-1 font-semibold">Average revenue per user</div>
+ <code className="break-words">sum(revenue) / nullIf(count(DISTINCT user_id), 0)</code>
+ <p className="mb-0 mt-1 text-secondary">
+ Replace revenue and user_id with your fields. nullIf avoids division by zero.
+ </p>
+ </div>
+ )}
</div>
</div>
</LemonModal>
diff --git a/products/business_intelligence/frontend/BIDataPaneField.tsx b/products/business_intelligence/frontend/BIDataPaneField.tsx
index 95fc000128c1..17e3f908c78c 100644
--- a/products/business_intelligence/frontend/BIDataPaneField.tsx
+++ b/products/business_intelligence/frontend/BIDataPaneField.tsx
@@ -17,7 +17,9 @@ import {
function FieldTypeGlyph({ field, measure }: { field: BIField; measure: boolean }): JSX.Element {
const glyph =
- field.type === 'date' || field.type === 'datetime' ? (
+ field.localDefinition?.kind === 'expression' ? (
+ 'ƒ'
+ ) : field.type === 'date' || field.type === 'datetime' ? (
<IconCalendar />
) : measure || ['integer', 'float', 'decimal'].includes(field.type) ? (
'#'
@@ -49,7 +51,7 @@ export function BIDataPaneField({
measure: boolean
path?: string[]
}): JSX.Element {
- const { addFieldToShelf, editLocalField } = useActions(biEditorLogic)
+ const { addFieldToShelf, editLocalField, editCalculatedField, removeLocalField } = useActions(biEditorLogic)
const addField = (field: BIField): void => {
const target = getBIDropTarget(field, 'rows')
addFieldToShelf(target.field, target.shelf)
@@ -60,7 +62,7 @@ export function BIDataPaneField({
key={field.id}
type="button"
draggable
- title={field.name}
+ title={field.localDefinition ? `${field.name} · worksheet-local field` : field.name}
className={cn(
'flex h-6 w-full min-w-0 cursor-grab items-center gap-1 rounded px-1 text-left text-xs hover:bg-fill-highlight-100',
'focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent'
@@ -85,19 +87,37 @@ export function BIDataPaneField({
{(field.localDefinition || isNumericBIField(field) || ['string', 'boolean'].includes(field.type)) && (
<LemonMenu
items={
- field.localDefinition
+ field.localDefinition?.kind === 'expression'
? [
+ { label: 'Edit calculated field', onClick: () => editCalculatedField(field) },
{
- label: 'Edit local definition',
- onClick: () => editLocalField(field, field.localDefinition!.kind),
+ label: 'Delete field and all uses',
+ status: 'danger',
+ onClick: () => removeLocalField(field.id),
},
]
- : [
- { label: 'Group categories', onClick: () => editLocalField(field, 'groups') },
- ...(isNumericBIField(field)
- ? [{ label: 'Create numeric bins', onClick: () => editLocalField(field, 'bins') }]
- : []),
- ]
+ : field.localDefinition
+ ? [
+ {
+ label: 'Edit local definition',
+ onClick: () =>
+ editLocalField(
+ field,
+ field.localDefinition?.kind === 'bins' ? 'bins' : 'groups'
+ ),
+ },
+ ]
+ : [
+ { label: 'Group categories', onClick: () => editLocalField(field, 'groups') },
+ ...(isNumericBIField(field)
+ ? [
+ {
+ label: 'Create numeric bins',
+ onClick: () => editLocalField(field, 'bins'),
+ },
+ ]
+ : []),
+ ]
}
>
<LemonButton
diff --git a/products/business_intelligence/frontend/BILocalFieldModal.tsx b/products/business_intelligence/frontend/BILocalFieldModal.tsx
index fbe5e0f505e3..4b4f63322e78 100644
--- a/products/business_intelligence/frontend/BILocalFieldModal.tsx
+++ b/products/business_intelligence/frontend/BILocalFieldModal.tsx
@@ -27,7 +27,7 @@ export function BILocalFieldModal(): JSX.Element | null {
})
const { options, optionsLoading, hasMore, optionsError } = useValues(valuesLogic)
const { setSearch, loadMore, loadOptions } = useActions(valuesLogic)
- if (!draft || !definition) {
+ if (!draft || !definition || definition.kind === 'expression') {
return null
}
const error = !draft.name.trim() ? 'Enter a name' : localFieldError(definition)
diff --git a/products/business_intelligence/frontend/biEditorLogic.test.ts b/products/business_intelligence/frontend/biEditorLogic.test.ts
index 66455e9ffff2..54355623e545 100644
--- a/products/business_intelligence/frontend/biEditorLogic.test.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.test.ts
@@ -425,6 +425,62 @@ describe('biEditorLogic', () => {
}
)
+ it.each(['dimension', 'measure'] as const)(
+ 'reuses, edits, clears, restores and deletes a worksheet-local %s',
+ (kind) => {
+ const logic = biEditorLogic({ tabId: TAB_ID })
+ logic.mount()
+ logic.actions.restoreState({ editorView: BIEditorView.BI, config })
+ const expression = kind === 'dimension' ? "coalesce(properties.plan, 'Unknown')" : 'sum(revenue)'
+ const editedExpression = kind === 'dimension' ? 'lower(properties.plan)' : 'avg(revenue)'
+ logic.actions.setCalculatedMeasureDraft({ index: null, kind, name: 'Local calculation', expression })
+ logic.actions.saveCalculatedMeasure()
+ const field = logic.values.config.localFields![0]
+ const shelf = kind === 'dimension' ? 'rows' : 'values'
+ logic.actions.duplicateField(shelf, kind === 'dimension' ? logic.values.config.rows.length - 1 : 0)
+ if (kind === 'dimension') {
+ logic.actions.addFieldToShelf(field, 'filters')
+ }
+ logic.actions.editCalculatedField(field)
+ logic.actions.setCalculatedMeasureDraft({
+ ...logic.values.calculatedMeasureDraft!,
+ name: 'Renamed calculation',
+ expression: editedExpression,
+ })
+ logic.actions.saveCalculatedMeasure()
+ expect(logic.values.config.localFields![0].name).toBe('Renamed calculation')
+ if (kind === 'dimension') {
+ expect(logic.values.config.rows.slice(-2).map((field) => field.expression)).toEqual([
+ editedExpression,
+ editedExpression,
+ ])
+ expect(
+ logic.values.config.filters.find((filter) => filter.field.id === field.id)?.field.expression
+ ).toBe(editedExpression)
+ } else {
+ expect(logic.values.config.values.map((value) => value.customExpression)).toEqual([
+ editedExpression,
+ editedExpression,
+ ])
+ }
+ const saved = parseBIEditorState(BIEditorView.BI, JSON.stringify(logic.values.config))!
+ logic.actions.resetConfig()
+ expect(logic.values.config.localFields).toEqual(saved.config.localFields)
+ expect(
+ logic.values.dataPaneFields[kind === 'dimension' ? 'dimensions' : 'measures'].some(
+ (field) => field.name === 'Renamed calculation'
+ )
+ ).toBe(true)
+ logic.actions.restoreState(saved)
+ logic.actions.removeLocalField(field.id)
+ expect(logic.values.config.localFields).toEqual([])
+ expect(logic.values.config.filters.some((filter) => filter.field.id === field.id)).toBe(false)
+ expect(logic.values.config.values.some((value) => value.field.id === field.id)).toBe(false)
+ expect(logic.values.config.rows.some((row) => (row.localFieldId ?? row.id) === field.id)).toBe(false)
+ logic.unmount()
+ }
+ )
+
it('creates and edits a calculated measure without applying canceled drafts or losing its sort', () => {
const biLogic = biEditorLogic({ tabId: TAB_ID })
biLogic.mount()
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index e16200065552..7075d2ad58b3 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -48,10 +48,11 @@ import {
getBISortOptions,
getBIValueSortKey,
isBIFieldCompatible,
+ isBIMeasureField,
normalizeBIConfig,
} from 'products/business_intelligence/frontend/biEditorTypes'
-import { localFieldError, localFieldExpression, upsertBILocalField } from './biLocalFields'
+import { getBILocalFields, localFieldError, localFieldExpression, upsertBILocalField } from './biLocalFields'
import { matchesBIFieldSearch } from './biPropertyFields'
import { getBIDateField } from './biQueryFilters'
@@ -63,6 +64,9 @@ export interface BICalculatedMeasureDraft {
index: number | null
name: string
expression: string
+ kind?: 'dimension' | 'measure'
+ fieldId?: string
+ type?: BIField['type']
}
function freshBIConfig(): BIConfig {
@@ -139,6 +143,9 @@ function addFieldToConfig(config: BIConfig, field: BIField, shelf: BIShelf): BIC
const source = config.source ?? field.source
const sourceConfig = config.source ? config : setDataSourceInConfig(config, source)
+ if (field.localDefinition?.kind === 'expression' && field.localDefinition.aggregate && shelf === 'filters') {
+ return config
+ }
switch (shelf) {
case 'rows':
case 'columns':
@@ -147,7 +154,12 @@ function addFieldToConfig(config: BIConfig, field: BIField, shelf: BIShelf): BIC
}
return { ...sourceConfig, source, [shelf]: [...sourceConfig[shelf], field] }
case 'values':
- return addValueToConfig(sourceConfig, { field, aggregation: defaultAggregationForField(field) })
+ return addValueToConfig(
+ sourceConfig,
+ field.localDefinition?.kind === 'expression' && field.localDefinition.aggregate
+ ? { field, aggregation: 'custom', customExpression: field.expression, label: field.name }
+ : { field, aggregation: defaultAggregationForField(field) }
+ )
case 'filters':
if (
sourceConfig.filters.some(
@@ -350,6 +362,7 @@ export interface biEditorLogicValues {
activeMeasureSettingsIndex: number | null
autoUpdate: boolean
availableDataSources: BIDataSource[]
+ calculatedFieldError: string | undefined
calculatedMeasureDraft: BICalculatedMeasureDraft | null
chartFits: Partial<Record<ChartDisplayType, BIChartFit>>
chartTypesOpen: boolean
@@ -420,6 +433,9 @@ export interface biEditorLogicActions {
index: number
shelf: 'columns' | 'rows' | 'values'
}
+ editCalculatedField: (field?: BIField) => {
+ field: BIField | undefined
+ }
editCalculatedMeasure: (index?: number | null) => {
index: number | null
}
@@ -451,6 +467,9 @@ export interface biEditorLogicActions {
index: number
shelf: BIShelf
}
+ removeLocalField: (fieldId: string) => {
+ fieldId: string
+ }
removeResultFilter: (id: string) => {
id: string
}
@@ -650,6 +669,10 @@ export interface biEditorLogicActions {
export interface biEditorLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ calculatedFieldError: (
+ calculatedMeasureDraft: BICalculatedMeasureDraft | null,
+ config: BIConfig
+ ) => string | undefined
chartTypesOpen: (showMeOpen: boolean) => boolean
availableDataSources: (
allTables: DatabaseSchemaTable[],
@@ -730,6 +753,8 @@ export const biEditorLogic = kea<biEditorLogicType>([
}),
setMeasureShelf: (index: number, shelf: 'rows' | 'columns') => ({ index, shelf }),
swapRowsAndColumns: true,
+ editCalculatedField: (field?: BIField) => ({ field }),
+ removeLocalField: (fieldId: string) => ({ fieldId }),
duplicateField: (shelf: Exclude<BIShelf, 'filters'>, index: number) => ({ shelf, index, fieldId: uuid() }),
setFieldDatePart: (shelf: BIShelf, index: number, datePart: BIField['datePart']) => ({
shelf,
@@ -868,19 +893,63 @@ export const biEditorLogic = kea<biEditorLogicType>([
return config
}
const existing = draft.index === null ? null : config.values[draft.index]
- const value = {
- ...existing,
- field: existing?.field ?? { ...blankField(config.source, fieldId), type: 'float' as const },
- aggregation: 'custom' as const,
- customExpression: draft.expression.trim(),
- label: draft.name.trim(),
+ const id =
+ draft.fieldId ?? existing?.field.localFieldId ?? (existing?.label ? existing.field.id : fieldId)
+ const aggregate = draft.kind !== 'dimension'
+ const field: BIField = {
+ ...blankField(config.source, id),
+ name: draft.name.trim(),
+ expression: draft.expression.trim(),
+ type: draft.type ?? (aggregate ? 'float' : 'string'),
+ localDefinition: { kind: 'expression', expression: draft.expression.trim(), aggregate },
}
- return draft.index === null
- ? addValueToConfig(config, value)
- : {
- ...config,
- values: config.values.map((current, index) => (index === draft.index ? value : current)),
- }
+ const updated = upsertBILocalField({ ...config, localFields: getBILocalFields(config) }, field)
+ if (existing && existing.field.id !== id && !existing.field.localFieldId) {
+ return {
+ ...updated,
+ values: updated.values.map((value, index) =>
+ index === draft.index
+ ? {
+ ...value,
+ field,
+ aggregation: 'custom',
+ customExpression: field.expression,
+ label: field.name,
+ }
+ : value
+ ),
+ }
+ }
+ if (draft.fieldId || existing) {
+ return updated
+ }
+ return aggregate
+ ? addValueToConfig(updated, {
+ field,
+ aggregation: 'custom',
+ customExpression: field.expression,
+ label: field.name,
+ })
+ : addFieldToConfig(updated, field, 'rows')
+ },
+ removeLocalField: (config, { fieldId }) => {
+ const matches = (field: BIField): boolean => (field.localFieldId ?? field.id) === fieldId
+ let next = {
+ ...config,
+ localFields: getBILocalFields(config).filter((field) => field.id !== fieldId),
+ }
+ for (let index = next.values.length - 1; index >= 0; index--) {
+ if (matches(next.values[index].field)) {
+ next = { ...removeFieldFromConfig(next, 'values', index), localFields: next.localFields }
+ }
+ }
+ return normalizeBIConfig({
+ ...next,
+ rows: next.rows.filter((field) => !matches(field)),
+ columns: next.columns.filter((field) => !matches(field)),
+ filters: next.filters.filter((filter) => !matches(filter.field)),
+ dateField: next.dateField && matches(next.dateField) ? undefined : next.dateField,
+ })
},
addFieldToShelf: (config, { field, shelf }) => addFieldToConfig(config, field, shelf),
setFilterGroup: (config, { scope, group }) => ({
@@ -1049,7 +1118,21 @@ export const biEditorLogic = kea<biEditorLogicType>([
return value ? { ...config, values: [...config.values, { ...value }] } : config
}
const field = config[shelf][index]
- return field ? { ...config, [shelf]: [...config[shelf], { ...field, id: fieldId }] } : config
+ return field
+ ? {
+ ...config,
+ [shelf]: [
+ ...config[shelf],
+ {
+ ...field,
+ id: fieldId,
+ localFieldId: field.localDefinition
+ ? (field.localFieldId ?? field.id)
+ : undefined,
+ },
+ ],
+ }
+ : config
},
setValueCustomExpression: (config, { index, customExpression }) => ({
...config,
@@ -1067,7 +1150,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
resetConfig: (config) => ({
...freshBIConfig(),
source: config.source,
- localFields: config.localFields,
+ localFields: getBILocalFields(config),
dateField: config.dateField,
dateRange: config.dateRange,
}),
@@ -1075,6 +1158,30 @@ export const biEditorLogic = kea<biEditorLogicType>([
],
})),
selectors({
+ calculatedFieldError: [
+ (s) => [s.calculatedMeasureDraft, s.config],
+ (draft: BICalculatedMeasureDraft | null, config: BIConfig): string | undefined => {
+ if (!draft?.name.trim()) {
+ return 'Enter a name for this field'
+ }
+ if (!draft.expression.trim()) {
+ return 'Enter a HogQL expression'
+ }
+ const existingId =
+ draft.fieldId ??
+ (draft.index === null
+ ? undefined
+ : (config.values[draft.index]?.field.localFieldId ?? config.values[draft.index]?.field.id))
+ if (
+ getBILocalFields(config).some(
+ (field) =>
+ field.id !== existingId && field.name.toLowerCase() === draft.name.trim().toLowerCase()
+ )
+ ) {
+ return 'A local field with this name already exists'
+ }
+ },
+ ],
chartTypesOpen: [(s) => [s.showMeOpen], (open: boolean): boolean => open],
availableDataSources: [
(selectors) => [selectors.allTables, selectors.posthogTables, selectors.databaseConnectionId],
@@ -1135,8 +1242,15 @@ export const biEditorLogic = kea<biEditorLogicType>([
allTables.find((table) => table.name === config.source?.table),
config.source
),
+ measures: [
+ ...getBILocalFields(config).filter(isBIMeasureField),
+ ...getBIDataPaneFields(
+ allTables.find((table) => table.name === config.source?.table),
+ config.source
+ ).measures,
+ ],
dimensions: [
- ...(config.localFields ?? []),
+ ...getBILocalFields(config).filter((field) => !isBIMeasureField(field)),
...getBIDataPaneFields(
allTables.find((table) => table.name === config.source?.table),
config.source
@@ -1216,6 +1330,23 @@ export const biEditorLogic = kea<biEditorLogicType>([
captureBIWorksheetAction('local_field_saved', values.config)
actions.runAfterChange()
},
+ editCalculatedField: ({ field }) => {
+ if (!values.config.source) {
+ return
+ }
+ actions.setCalculatedMeasureDraft({
+ index: null,
+ fieldId: field?.id,
+ kind:
+ field?.localDefinition?.kind === 'expression' && field.localDefinition.aggregate
+ ? 'measure'
+ : 'dimension',
+ name: field?.name ?? '',
+ expression: field?.expression ?? '',
+ type: field?.type ?? 'string',
+ })
+ },
+ removeLocalField: () => actions.runAfterChange(),
editCalculatedMeasure: ({ index }) => {
if (!values.config.source) {
return
@@ -1226,11 +1357,14 @@ export const biEditorLogic = kea<biEditorLogicType>([
index,
name: value?.label ?? '',
expression: value?.customExpression ?? '',
+ kind: 'measure',
+ fieldId: value?.field.localFieldId,
+ type: value?.field.type ?? 'float',
})
},
saveCalculatedMeasure: () => {
const draft = values.calculatedMeasureDraft
- if (draft?.name.trim() && draft.expression.trim()) {
+ if (draft && !values.calculatedFieldError) {
actions.upsertCalculatedMeasure(draft)
}
},
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 4523d09a1f7f..92cde7c8f817 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -260,6 +260,9 @@ const IDENTIFIER_FIELD_NAME_REGEX = /(^|_)(id|uuid)$/i
/** Numeric fields that are not identifiers aggregate by default, like measures in a BI tool. */
export function isBIMeasureField(field: BIField): boolean {
+ if (field.localDefinition?.kind === 'expression') {
+ return field.localDefinition.aggregate
+ }
return (
!field.localDefinition &&
isNumericBIField(field) &&
@@ -443,6 +446,7 @@ function parseBIFieldValue(value: unknown): BIField | null {
typeof candidate.name !== 'string' ||
typeof candidate.expression !== 'string' ||
typeof candidate.type !== 'string' ||
+ (candidate.localFieldId !== undefined && typeof candidate.localFieldId !== 'string') ||
(candidate.dateBucket !== undefined &&
(!BI_DATE_BUCKETS.has(candidate.dateBucket) ||
(candidate.type !== 'date' && candidate.type !== 'datetime'))) ||
diff --git a/products/business_intelligence/frontend/biLocalFields.test.ts b/products/business_intelligence/frontend/biLocalFields.test.ts
index fd9e440ecc3b..39f640f6caaa 100644
--- a/products/business_intelligence/frontend/biLocalFields.test.ts
+++ b/products/business_intelligence/frontend/biLocalFields.test.ts
@@ -4,6 +4,8 @@ import { BIEditorView, buildBIQuery, DEFAULT_BI_CONFIG, parseBIEditorState } fro
import { localFieldError, localFieldExpression, upsertBILocalField } from './biLocalFields'
it.each<BILocalFieldDefinition>([
+ { kind: 'expression', expression: "coalesce(properties.plan, 'Unknown')", aggregate: false },
+ { kind: 'expression', expression: 'sum(properties.amount)', aggregate: true },
{
kind: 'groups',
expression: 'properties.country',
diff --git a/products/business_intelligence/frontend/biLocalFields.ts b/products/business_intelligence/frontend/biLocalFields.ts
index 8f47ca5eb1a8..f27df09d07fc 100644
--- a/products/business_intelligence/frontend/biLocalFields.ts
+++ b/products/business_intelligence/frontend/biLocalFields.ts
@@ -5,6 +5,9 @@ export function localFieldError(definition: BILocalFieldDefinition): string | un
if (!definition || typeof definition.expression !== 'string' || !definition.expression.trim()) {
return 'Choose a source field'
}
+ if (definition.kind === 'expression') {
+ return typeof definition.aggregate === 'boolean' ? undefined : 'Choose a dimension or measure'
+ }
if (definition.kind === 'bins') {
return Number.isFinite(definition.width) && definition.width > 0 && Number.isFinite(definition.origin)
? undefined
@@ -48,6 +51,9 @@ export function localFieldError(definition: BILocalFieldDefinition): string | un
}
export function localFieldExpression(definition: BILocalFieldDefinition): string {
+ if (definition.kind === 'expression') {
+ return definition.expression.trim()
+ }
if (definition.kind === 'bins') {
return `(floor(((${definition.expression}) - ${definition.origin}) / ${definition.width}) * ${definition.width} + ${definition.origin})`
}
@@ -60,13 +66,53 @@ export function localFieldExpression(definition: BILocalFieldDefinition): string
}
export function upsertBILocalField(config: BIConfig, field: BIField): BIConfig {
- const replace = (current: BIField): BIField => (current.id === field.id ? field : current)
+ const matches = (current: BIField): boolean => (current.localFieldId ?? current.id) === field.id
+ const replace = (current: BIField): BIField =>
+ matches(current)
+ ? {
+ ...current,
+ ...field,
+ id: current.id,
+ localFieldId: field.id,
+ dateBucket: ['date', 'datetime'].includes(field.type) ? current.dateBucket : undefined,
+ datePart: ['date', 'datetime'].includes(field.type) ? current.datePart : undefined,
+ }
+ : current
return {
...config,
localFields: [...(config.localFields ?? []).filter((current) => current.id !== field.id), field],
rows: config.rows.map(replace),
columns: config.columns.map(replace),
- values: config.values.map((value) => ({ ...value, field: replace(value.field) })),
+ values: config.values.map((value) => ({
+ ...value,
+ field: replace(value.field),
+ ...(matches(value.field) && field.localDefinition?.kind === 'expression' && field.localDefinition.aggregate
+ ? { aggregation: 'custom' as const, customExpression: field.expression, label: field.name }
+ : {}),
+ })),
filters: config.filters.map((filter) => ({ ...filter, field: replace(filter.field) })),
+ dateField: config.dateField ? replace(config.dateField) : config.dateField,
+ }
+}
+
+export function getBILocalFields(config: BIConfig): BIField[] {
+ const fields = [...(config.localFields ?? [])]
+ for (const value of config.values) {
+ const id = value.field.localFieldId ?? value.field.id
+ if (
+ value.aggregation === 'custom' &&
+ value.label &&
+ value.customExpression?.trim() &&
+ !fields.some((field) => field.id === id)
+ ) {
+ fields.push({
+ ...value.field,
+ id,
+ name: value.label,
+ expression: value.customExpression,
+ localDefinition: { kind: 'expression', aggregate: true, expression: value.customExpression },
+ })
+ }
}
+ return fields
}
diff --git a/products/business_intelligence/frontend/components/BIDataPane.tsx b/products/business_intelligence/frontend/components/BIDataPane.tsx
index 48cc2fa3d437..460a6fbcf0bc 100644
--- a/products/business_intelligence/frontend/components/BIDataPane.tsx
+++ b/products/business_intelligence/frontend/components/BIDataPane.tsx
@@ -20,7 +20,7 @@ export function BIDataPane({ tabId }: { tabId: string }): JSX.Element {
dataPaneSearch,
filteredDataPaneFields,
} = useValues(biEditorLogic)
- const { editCalculatedMeasure, hydrateTableFields, setDataPaneSearch } = useActions(biEditorLogic)
+ const { editCalculatedField, hydrateTableFields, setDataPaneSearch } = useActions(biEditorLogic)
const hasFields = dataPaneFields.dimensions.length > 0 || dataPaneFields.measures.length > 0
const hasMatches = filteredDataPaneFields.dimensions.length > 0 || filteredDataPaneFields.measures.length > 0
@@ -95,11 +95,11 @@ export function BIDataPane({ tabId }: { tabId: string }): JSX.Element {
size="xsmall"
fullWidth
type="secondary"
- onClick={() => editCalculatedMeasure()}
+ onClick={() => editCalculatedField()}
disabledReason={!config.source ? 'Select a data source first' : undefined}
data-attr="bi-editor-add-calculated-measure"
>
- Add calculated measure
+ Add calculated field
</LemonButton>
</div>
</div>
diff --git a/products/business_intelligence/frontend/components/BIFieldPill.tsx b/products/business_intelligence/frontend/components/BIFieldPill.tsx
index c65915d5d616..5d12d803a8ed 100644
--- a/products/business_intelligence/frontend/components/BIFieldPill.tsx
+++ b/products/business_intelligence/frontend/components/BIFieldPill.tsx
@@ -37,6 +37,7 @@ export function BIFieldPill({
addFieldToShelf,
convertMeasureToDimension,
duplicateField,
+ editCalculatedField,
editCalculatedMeasure,
moveFieldToShelf,
removeFieldFromShelf,
@@ -125,8 +126,15 @@ export function BIFieldPill({
moveFieldToShelf('values', index, value?.shelf === 'columns' ? 'rows' : 'columns'),
}
: null,
- !isCalculatedMeasure ? { label: 'Edit field expression', onClick: () => setEditing('field') } : null,
- value?.aggregation === 'custom'
+ field.localDefinition?.kind === 'expression'
+ ? {
+ label: 'Edit calculated field',
+ onClick: () => editCalculatedField({ ...field, id: field.localFieldId ?? field.id }),
+ }
+ : !isCalculatedMeasure
+ ? { label: 'Edit field expression', onClick: () => setEditing('field') }
+ : null,
+ value?.aggregation === 'custom' && field.localDefinition?.kind !== 'expression'
? { label: 'Edit calculated measure', onClick: () => editCalculatedMeasure(index) }
: null,
sortKey
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 11b5a6891e00..73c82df7493a 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9441,19 +9441,25 @@ export const DatePartApi = {
DayOfWeek: 'day_of_week',
} as const
+export interface BILocalFieldDefinition1Api {
+ aggregate: boolean
+ expression: string
+ kind?: 'expression'
+}
+
export interface BICategoryGroupApi {
name: string
values: string[]
}
-export interface BILocalFieldDefinition1Api {
+export interface BILocalFieldDefinition2Api {
expression: string
groups: BICategoryGroupApi[]
kind?: 'groups'
other: string
}
-export interface BILocalFieldDefinition2Api {
+export interface BILocalFieldDefinition3Api {
expression: string
kind?: 'bins'
origin: number
@@ -9492,7 +9498,8 @@ export interface BIFieldApi {
datePart?: DatePartApi | null
expression: string
id: string
- localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | null
+ localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | BILocalFieldDefinition3Api | null
+ localFieldId?: string | null
name: string
source: BIDataSourceApi
type: DatabaseSerializedFieldTypeApi
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index b8ba40d4380c..e6529172b713 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8305,19 +8305,25 @@ export const DatePartApi = {
DayOfWeek: 'day_of_week',
} as const
+export interface BILocalFieldDefinition1Api {
+ aggregate: boolean
+ expression: string
+ kind?: 'expression'
+}
+
export interface BICategoryGroupApi {
name: string
values: string[]
}
-export interface BILocalFieldDefinition1Api {
+export interface BILocalFieldDefinition2Api {
expression: string
groups: BICategoryGroupApi[]
kind?: 'groups'
other: string
}
-export interface BILocalFieldDefinition2Api {
+export interface BILocalFieldDefinition3Api {
expression: string
kind?: 'bins'
origin: number
@@ -8356,7 +8362,8 @@ export interface BIFieldApi {
datePart?: DatePartApi | null
expression: string
id: string
- localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | null
+ localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | BILocalFieldDefinition3Api | null
+ localFieldId?: string | null
name: string
source: BIDataSourceApi
type: DatabaseSerializedFieldTypeApi
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 642841a208a6..8e189eafd351 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10745,19 +10745,25 @@ export namespace Schemas {
DayOfWeek: 'day_of_week',
} as const;
+ export interface BILocalFieldDefinition1 {
+ aggregate: boolean;
+ expression: string;
+ kind?: 'expression';
+ }
+
export interface BICategoryGroup {
name: string;
values: string[];
}
- export interface BILocalFieldDefinition1 {
+ export interface BILocalFieldDefinition2 {
expression: string;
groups: BICategoryGroup[];
kind?: 'groups';
other: string;
}
- export interface BILocalFieldDefinition2 {
+ export interface BILocalFieldDefinition3 {
expression: string;
kind?: 'bins';
origin: number;
@@ -10796,7 +10802,8 @@ export namespace Schemas {
datePart?: DatePart | null;
expression: string;
id: string;
- localDefinition?: BILocalFieldDefinition1 | BILocalFieldDefinition2 | null;
+ localDefinition?: BILocalFieldDefinition1 | BILocalFieldDefinition2 | BILocalFieldDefinition3 | null;
+ localFieldId?: string | null;
name: string;
source: BIDataSource;
type: DatabaseSerializedFieldType;