: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(sql-editor): add named calculated measures to bi worksheets (#110995)
Marius Andra427607ed9d89
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 39923aab7804..2db3fd0fff4d 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -12,6 +12,17 @@ The SQL editor keeps unrun edits in browser storage, scoped to the user, projectAn **Edited** label marks changes to a saved view or insight. **Discard changes** restores the saved copy already loaded in memory, then refreshes it from the server. The refresh preserves edits made after discarding.Insights can be saved or updated before running the SQL. Updating a view still requires a successful run of the current SQL so its result types match the saved query. **Continue in a notebook** is in the update button's dropdown for saved views and insights.+## Calculated measures in BI mode++With `SQL_EDITOR_BI_MODE` enabled, select a table in the SQL editor's BI mode 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.+## Apple Ads in Marketing analyticsMarketing analytics support is controlled by the boolean organization flag `marketing-analytics-apple-ads` and is off by default.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0ffaf68dd8d3..4179aeda08a2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9502,6 +9502,10 @@ snapshots:hash: v1.k794b7964.22840c30d80b9e1a3bd41d5a31af2ab81a54d9f90fb82d540fb9494b44cda050.oC_UUgUXZVqKMZ6LuInaQADAzqeWAvw2dZ8T5eENhIQscenes-app-data-warehouse-settings-schemas--multi-schema--light:hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0+ scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--dark:+ hash: v1.k794b7964.083c256d8a7d763c5ba0816e768593591842626f2c634a94cd85adc4a45612b0.0L48DpV5Yvh1QvTM0arKobQZMFoe2aNO8giOvazDdHw+ scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:+ hash: v1.k794b7964.b5765e1b7a155becef5d85878017eee5ff92bf0941fa8fb4cb27ca70c7b115a3.MHmkJ7F78j_l_g-WUGNy0sozpFp3MZuQQTkCzMTpE_sscenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:hash: v1.k794b7964.c658d01e1ed459e380f64ae18cc893a3bdd4d14d60924691224143b4133d304c.bJ8fJvADbAl-CJHuO6-1i9Ng1abedjo0nuR3uHQ42KMscenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsxindex 46041708a098..6d683c161e3a 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx@@ -410,6 +410,25 @@ export const BIModeWorksheet: Story = {},}+export const BICalculatedMeasureEditor: Story = {+ ...BIModeWorksheet,+ parameters: {+ ...BIModeWorksheet.parameters,+ testOptions: {+ waitForSelector: '[data-attr="bi-calculated-measure-modal"] .monaco-editor',+ viewport: { width: 1050, height: 900 },+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const addMeasure = await canvas.findByText('Add calculated measure', {}, { timeout: 15000 })+ await waitFor(() => expect(addMeasure.closest('button')).toBeEnabled())+ await userEvent.click(addMeasure)+ const modal = within(canvasElement.ownerDocument.body)+ await userEvent.type(await modal.findByLabelText('Name'), 'ARPU')+ },+}+export const LazySchema: Story = {parameters: {pageUrl: urls.sqlEditor({ query: 'SELECT * FROM events LIMIT 100' }),diff --git a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsxindex 858c0c898853..ac7cdf45fe5d 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx@@ -4,6 +4,8 @@ import type { ReactNode } from 'react'import { Resizer } from 'lib/components/Resizer/Resizer'import { IconTableChart } from 'lib/lemon-ui/icons'+import { BICalculatedMeasureModal } from 'products/data_warehouse/frontend/bi/BICalculatedMeasureModal'+import { editorSizingLogic } from '../editorSizingLogic'import { biEditorLogic } from './biEditorLogic'import { BI_SHELF_PILL_DRAG_MIME_TYPE, parseBIShelfPillDragData } from './biEditorTypes'@@ -44,6 +46,7 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNoonDragEnd={() => setActiveDropShelf(null)}><BIToolbar />+ <BICalculatedMeasureModal /><div className="flex min-h-0 flex-1"><divclassName="relative flex w-[var(--bi-side-pane-width)] shrink-0 flex-col border-r @4xl/bi-editor:w-[calc(var(--bi-side-pane-width)+12rem)] @4xl/bi-editor:flex-row"diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.tsindex a46345cf2ebe..1cacebff4e48 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts@@ -44,6 +44,12 @@ export interface BIEditorLogicProps {tabId: string}+export interface BICalculatedMeasureDraft {+ index: number | null+ name: string+ expression: string+}+function freshBIConfig(): BIConfig {return {...DEFAULT_BI_CONFIG,@@ -139,6 +145,9 @@ function fieldOnShelf(config: BIConfig, shelf: BIShelf, index: number): BIField}function moveFieldInConfig(config: BIConfig, fromShelf: BIShelf, fromIndex: number, toShelf: BIShelf): BIConfig {+ if (fromShelf === 'values' && config.values[fromIndex]?.label) {+ return config+ }const field = fieldOnShelf(config, fromShelf, fromIndex)if (!field || fromShelf === toShelf) {return config@@ -230,6 +239,7 @@ export interface biEditorLogicValues {activeExpressionEditorTarget: 'aggregation' | 'field'autoUpdate: booleanavailableDataSources: BIDataSource[]+ calculatedMeasureDraft: BICalculatedMeasureDraft | nullchartFits: Partial<Record<ChartDisplayType, BIChartFit>>config: BIConfigdataPaneFields: BIDataPaneFields@@ -289,6 +299,9 @@ export interface biEditorLogicActions {clearActiveDropShelf: (shelf: BIShelf) => {shelf: BIShelf}+ editCalculatedMeasure: (index?: number | null) => {+ index: number | null+ }moveFieldToShelf: (fromShelf: BIShelf,fromIndex: number,@@ -321,6 +334,9 @@ export interface biEditorLogicActions {runAfterChange: () => {value: true}+ saveCalculatedMeasure: () => {+ value: true+ }setActiveDropShelf: (shelf: BIShelf | null) => {shelf: BIShelf | null}@@ -334,6 +350,9 @@ export interface biEditorLogicActions {setAutoUpdate: (autoUpdate: boolean) => {autoUpdate: boolean}+ setCalculatedMeasureDraft: (draft: BICalculatedMeasureDraft | null) => {+ draft: BICalculatedMeasureDraft | null+ }setChartType: (chartType: ChartDisplayType) => {chartType: ChartDisplayType}@@ -417,6 +436,10 @@ export interface biEditorLogicActions {syncGeneratedQuery: () => {value: true}+ upsertCalculatedMeasure: (draft: BICalculatedMeasureDraft) => {+ draft: BICalculatedMeasureDraft+ fieldId: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -440,9 +463,14 @@ export interface biEditorLogicMeta {dataPaneFieldsLoading: (config: BIConfig,tableFieldsStatus: TableFieldsStatus,- databaseLoading: boolean+ databaseLoading: boolean,+ databaseConnectionId: string | null+ ) => boolean+ dataPaneFieldsError: (+ config: BIConfig,+ tableFieldsStatus: TableFieldsStatus,+ databaseConnectionId: string | null) => boolean- dataPaneFieldsError: (config: BIConfig, tableFieldsStatus: TableFieldsStatus) => booleanfilteredDataPaneFields: (dataPaneFields: BIDataPaneFields, dataPaneSearch: string) => BIDataPaneFields}}@@ -484,6 +512,10 @@ export const biEditorLogic = kea<biEditorLogicType>([persistState: (editorView: BIEditorView, config: BIConfig) => ({ editorView, config }),addFieldToShelf: (field: BIField, shelf: BIShelf) => ({ field, shelf }),addBlankFieldToShelf: (shelf: BIShelf) => ({ shelf, fieldId: `bi-blank-${uuid()}` }),+ editCalculatedMeasure: (index: number | null = null) => ({ index }),+ setCalculatedMeasureDraft: (draft: BICalculatedMeasureDraft | null) => ({ draft }),+ saveCalculatedMeasure: true,+ upsertCalculatedMeasure: (draft: BICalculatedMeasureDraft) => ({ draft, fieldId: `bi-calculated-${uuid()}` }),clearActiveDropShelf: (shelf: BIShelf) => ({ shelf }),moveFieldToShelf: (fromShelf: BIShelf, fromIndex: number, toShelf: BIShelf) => ({fromShelf,@@ -521,6 +553,19 @@ export const biEditorLogic = kea<biEditorLogicType>([syncGeneratedQuery: true,}),reducers(() => ({+ calculatedMeasureDraft: [+ null as BICalculatedMeasureDraft | null,+ {+ setCalculatedMeasureDraft: (_, { draft }) => draft,+ upsertCalculatedMeasure: () => null,+ setDataSource: () => null,+ resetConfig: () => null,+ restoreState: () => null,+ setEditorView: () => null,+ removeFieldFromShelf: () => null,+ moveFieldToShelf: () => null,+ },+ ],dragSessionId: [uuid(), {}],activeDropShelf: [null as BIShelf | null,@@ -580,6 +625,25 @@ export const biEditorLogic = kea<biEditorLogicType>([config: [freshBIConfig(),{+ upsertCalculatedMeasure: (config, { draft, fieldId }) => {+ if (!config.source) {+ return config+ }+ const existing = draft.index === null ? null : config.values[draft.index]+ const value = {+ field: existing?.field ?? { ...blankField(config.source, fieldId), type: 'float' as const },+ aggregation: 'custom' as const,+ customExpression: draft.expression.trim(),+ label: draft.name.trim(),+ }+ return {+ ...config,+ values:+ draft.index === null+ ? [...config.values, value]+ : config.values.map((current, index) => (index === draft.index ? value : current)),+ }+ },addFieldToShelf: (config, { field, shelf }) => addFieldToConfig(config, field, shelf),addBlankFieldToShelf: (config, { shelf, fieldId }) =>config.source ? addFieldToConfig(config, blankField(config.source, fieldId), shelf) : config,@@ -695,14 +759,28 @@ export const biEditorLogic = kea<biEditorLogicType>([: { dimensions: [], measures: [] },],dataPaneFieldsLoading: [- (selectors) => [selectors.config, selectors.tableFieldsStatus, selectors.databaseLoading],- (config: BIConfig, tableFieldsStatus: TableFieldsStatus, databaseLoading: boolean): boolean =>- !!config.source && (databaseLoading || tableFieldsStatus[config.source.table] === 'loading'),+ (selectors) => [+ selectors.config,+ selectors.tableFieldsStatus,+ selectors.databaseLoading,+ selectors.databaseConnectionId,+ ],+ (+ config: BIConfig,+ tableFieldsStatus: TableFieldsStatus,+ databaseLoading: boolean,+ connectionId: string | null+ ): boolean =>+ !!config.source &&+ (config.source.connectionId ?? null) === connectionId &&+ (databaseLoading || tableFieldsStatus[config.source.table] === 'loading'),],dataPaneFieldsError: [- (selectors) => [selectors.config, selectors.tableFieldsStatus],- (config: BIConfig, tableFieldsStatus: TableFieldsStatus): boolean =>- !!config.source && tableFieldsStatus[config.source.table] === 'error',+ (selectors) => [selectors.config, selectors.tableFieldsStatus, selectors.databaseConnectionId],+ (config: BIConfig, tableFieldsStatus: TableFieldsStatus, connectionId: string | null): boolean =>+ !!config.source &&+ (config.source.connectionId ?? null) === connectionId &&+ tableFieldsStatus[config.source.table] === 'error',],filteredDataPaneFields: [(selectors) => [selectors.dataPaneFields, selectors.dataPaneSearch],@@ -720,6 +798,25 @@ export const biEditorLogic = kea<biEditorLogicType>([],}),listeners(({ actions, props: logicProps, values, cache }) => ({+ editCalculatedMeasure: ({ index }) => {+ if (!values.config.source) {+ return+ }+ const value = index === null ? null : values.config.values[index]+ actions.setActiveExpressionEditorId(null)+ actions.setCalculatedMeasureDraft({+ index,+ name: value?.label ?? '',+ expression: value?.customExpression ?? '',+ })+ },+ saveCalculatedMeasure: () => {+ const draft = values.calculatedMeasureDraft+ if (draft?.name.trim() && draft.expression.trim()) {+ actions.upsertCalculatedMeasure(draft)+ }+ },+ upsertCalculatedMeasure: () => actions.runAfterChange(),loadDatabaseSuccess: () => {if (values.config.source && (values.config.source.connectionId ?? null) === values.databaseConnectionId) {actions.hydrateTableFields([values.config.source.table])@@ -865,10 +962,11 @@ export const biEditorLogic = kea<biEditorLogicType>([})},})),- subscriptions(({ actions }) => ({+ subscriptions(({ actions, values }) => ({config: (config: BIConfig, oldConfig: BIConfig | undefined) => {if (config.source &&+ (config.source.connectionId ?? null) === values.databaseConnectionId &&(!oldConfig?.source || getBIDataSourceKey(config.source) !== getBIDataSourceKey(oldConfig.source))) {actions.hydrateTableFields([config.source.table])diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.tsindex 85ac2f71de4a..59f95a0a35ab 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts@@ -5,6 +5,7 @@ import {BIConfig,BIEditorView,BIField,+ DEFAULT_BI_CONFIG,buildBIQuery,createDefaultDateFilter,defaultAggregationForField,@@ -14,6 +15,7 @@ import {getBIFieldId,getBISortOptions,getBIValueSortKey,+ getBIValuePillLabel,isBIFieldCompatible,isBIMeasureField,parseBIEditorState,@@ -189,7 +191,15 @@ describe('BI editor query generation', () => {)})- it('keeps nested object paths and explicit SQL expressions in the generated query', () => {+ test.each([+ [undefined, 'custom_revenue'],+ ['ARPU', 'ARPU'],+ ['Revenue per user', '"Revenue per user"'],+ ['`Revenue`', '"`Revenue`"'],+ ['Revenue"quoted`', '`Revenue"quoted```'],+ ['properties', 'properties_2'],+ ['event', 'event_2'],+ ])('keeps SQL expressions and measure label %s through persistence', (label, alias) => {const browserField: BIField = {id: 'warehouse:events:properties',name: 'properties',@@ -197,7 +207,7 @@ describe('BI editor query generation', () => {type: 'json',source: { table: 'events' },}- const result = buildBIQuery({+ const config: BIConfig = {source: { table: 'events' },chartType: ChartDisplayType.ActionsBar,rows: [browserField],@@ -207,6 +217,7 @@ describe('BI editor query generation', () => {field: revenueField,aggregation: 'custom',customExpression: "sumIf(properties.revenue, event = 'purchase')",+ label,},],filters: [@@ -219,14 +230,51 @@ describe('BI editor query generation', () => {},],limit: 100,- })+ }+ const restored = parseBIEditorState(BIEditorView.BI, JSON.stringify(config))!.config+ const result = buildBIQuery(restored)expect(result?.query).toContain('properties.$browser')- expect(result?.query).toContain("sumIf(properties.revenue, event = 'purchase') AS custom_revenue")+ expect(result?.query).toContain(`sumIf(properties.revenue, event = 'purchase') AS ${alias}`)+ expect(getBIValuePillLabel(restored.values[0])).toBe(label ?? "sumIf(properties.revenue, event = 'purchase')")+ expect(getBISortOptions(restored).at(-1)?.label).toBe(label ?? "sumIf(properties.revenue, event = 'purchase')")expect(result?.query).toContain("timestamp > '2026-08-04 09:30:00'")expect(result?.query).toContain("properties.$browser != 'HeadlessChrome'")})+ test.each([ChartDisplayType.ActionsTable, ChartDisplayType.TwoDimensionalHeatmap])(+ 'disambiguates measure names from dimensions and generated aliases in %s',+ (chartType) => {+ const config: BIConfig = {+ ...DEFAULT_BI_CONFIG,+ source: eventField.source,+ chartType,+ rows: [eventField],+ values: [+ {+ field: revenueField,+ aggregation: 'custom',+ customExpression: 'sum(properties.revenue)',+ label: 'sum_revenue_2',+ },+ { field: revenueField, aggregation: 'sum' },+ { field: revenueField, aggregation: 'custom', customExpression: 'count(*)', label: 'event' },+ ],+ sort: { key: `values:${revenueField.id}:2`, direction: 'asc' },+ }+ const result = buildBIQuery(config)!+ expect(result.query).toContain('sum(properties.revenue) AS sum_revenue_2,')+ expect(result.query).toContain('sum(properties.revenue) AS sum_revenue_2_2,')+ expect(result.query).toContain('ORDER BY\n sum_revenue_2_2 ASC')+ expect(getBISortOptions(config).find(({ key }) => key === config.sort?.key)?.expression).toBe(+ 'sum_revenue_2_2'+ )+ if (chartType === ChartDisplayType.TwoDimensionalHeatmap) {+ expect(result.node.chartSettings?.heatmap?.valueColumn).toBe('sum_revenue_2')+ }+ }+ )+test.each([['events', 'timestamp'],['sessions', '$start_timestamp'],diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.tsindex e718db82de80..83d7304c97fe 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts@@ -4,7 +4,12 @@ import {DatabaseSerializedFieldType,NodeKind,} from '~/queries/schema/schema-general'-import { escapeDottedHogQLIdentifier, escapeHogQLString, escapePropertyAsHogQLIdentifier } from '~/queries/utils'+import {+ escapeDottedHogQLIdentifier,+ escapeHogQLString,+ escapePropertyAsHogQLIdentifier,+ escapeRawPropertyAsHogQLIdentifier,+} from '~/queries/utils'import { ChartDisplayType } from '~/types'export enum BIEditorView {@@ -77,6 +82,7 @@ export interface BIValue {field: BIFieldaggregation: BIAggregationcustomExpression?: string+ label?: string}export interface BIFilter {@@ -437,6 +443,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknowif (!field ||!BI_AGGREGATIONS.has(valueCandidate.aggregation as BIAggregation) ||+ (valueCandidate.label !== undefined && typeof valueCandidate.label !== 'string') ||(valueCandidate.customExpression !== undefined && typeof valueCandidate.customExpression !== 'string')) {return null@@ -445,6 +452,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknowfield,aggregation: valueCandidate.aggregation as BIAggregation,customExpression: valueCandidate.customExpression,+ label: valueCandidate.label,}}): null@@ -549,6 +557,9 @@ interface BIPivotAxis {}function aggregationAlias(value: BIValue, index: number): string {+ if (value.aggregation === 'custom' && value.label?.trim()) {+ return `${value.label.trim()}${index > 0 ? `_${index + 1}` : ''}`+ }return `${value.aggregation}_${sanitizeAlias(value.field.name)}${index > 0 ? `_${index + 1}` : ''}`}@@ -647,6 +658,7 @@ function filterExpression(filter: BIFilter): string | null {interface BIConfiguredValue {value: BIValueexpression: string+ alias: string}interface BIQueryParts {@@ -663,9 +675,42 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {.map((field, index) => ({ alias: dimensionAlias('column', field, index), field })).filter(({ field }) => field.expression.trim() || field.name.trim())const configuredValues = config.values- .map((value) => ({ value, expression: aggregationExpression(value) }))+ .map((value) => ({ value, expression: aggregationExpression(value), alias: '' })).filter((configuredValue): configuredValue is BIConfiguredValue => !!configuredValue.expression)+ const expressions = [+ ...rowDimensions.map(({ field }) => fieldExpression(field)),+ ...columnDimensions.map(({ field }) => fieldExpression(field)),+ ...configuredValues.map(({ expression }) => expression),+ ...config.filters.map((filter) => filter.customExpression || fieldExpression(filter.field)),+ ]+ const usedAliases = new Set([+ ...rowDimensions.map(({ alias }) => alias),+ ...columnDimensions.map(({ alias }) => alias),+ 'bi_rows',+ 'bi_columns',+ ])+ const reservedAliases = new Set(configuredValues.map(({ value }, index) => aggregationAlias(value, index)))+ configuredValues.forEach((configuredValue, index) => {+ const preferred = aggregationAlias(configuredValue.value, index)+ let alias = preferred+ let suffix = 2+ // Avoid shadowing identifiers even inside authored formulas and SQL filters.+ while (+ usedAliases.has(alias) ||+ expressions.some(+ (expression) =>+ expression.includes(alias) || expression.includes(escapeRawPropertyAsHogQLIdentifier(alias))+ )+ ) {+ do {+ alias = `${preferred}_${suffix++}`+ } while (reservedAliases.has(alias))+ }+ configuredValue.alias = alias+ usedAliases.add(alias)+ })+return { rowDimensions, columnDimensions, configuredValues }}@@ -680,7 +725,7 @@ const SORT_AGGREGATION_LABELS: Record<Exclude<BIAggregation, 'custom'>, string>function sortValueLabel(value: BIValue): string {if (value.aggregation === 'custom') {- return value.customExpression?.trim() || 'Custom value'+ return value.label?.trim() || value.customExpression?.trim() || 'Custom value'}return `${SORT_AGGREGATION_LABELS[value.aggregation]} of ${value.field.name || value.field.expression}`@@ -712,13 +757,13 @@ export function getBISortOptions(config: BIConfig): BISortOption[] {expression: fieldExpression(field),})),...(configuredValues.length > 0- ? configuredValues.map(({ value }, index) => {+ ? configuredValues.map(({ value, alias }) => {const occurrence = valueOccurrences.get(value.field.id) ?? 0valueOccurrences.set(value.field.id, occurrence + 1)return {key: occurrence === 0 ? `values:${value.field.id}` : `values:${value.field.id}:${occurrence + 1}`,label: sortValueLabel(value),- expression: escapePropertyAsHogQLIdentifier(aggregationAlias(value, index)),+ expression: escapeRawPropertyAsHogQLIdentifier(alias),}}): [{ key: 'values:count', label: 'Count', expression: 'count' }]),@@ -765,7 +810,7 @@ export function getBIFieldPillLabel(field: BIField): string {export function getBIValuePillLabel(value: BIValue): string {if (value.aggregation === 'custom') {- return value.customExpression?.trim() || 'New calculation'+ return value.label?.trim() || value.customExpression?.trim() || 'New calculation'}return `${PILL_AGGREGATION_PREFIXES[value.aggregation]}(${getBIFieldPillLabel(value.field)})`}@@ -793,9 +838,7 @@ function buildOrderByExpression(}const firstValueAlias =- configuredValues.length > 0- ? escapePropertyAsHogQLIdentifier(aggregationAlias(configuredValues[0].value, 0))- : 'count'+ configuredValues.length > 0 ? escapeRawPropertyAsHogQLIdentifier(configuredValues[0].alias) : 'count'return `${firstValueAlias} DESC`}@@ -818,8 +861,7 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {const valueExpressions =configuredValues.length > 0? configuredValues.map(- ({ value, expression }, index) =>- `${expression} AS ${escapePropertyAsHogQLIdentifier(aggregationAlias(value, index))}`+ ({ expression, alias }) => `${expression} AS ${escapeRawPropertyAsHogQLIdentifier(alias)}`): ['count(*) AS count']const selectExpressions = [...dimensionSelectExpressions, ...valueExpressions]@@ -858,7 +900,7 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {heatmap: {xAxisColumn: pivotColumnAxis?.alias,yAxisColumn: pivotRowAxis?.alias,- valueColumn: configuredValues[0] ? aggregationAlias(configuredValues[0].value, 0) : 'count',+ valueColumn: configuredValues[0]?.alias ?? 'count',xAxisLabel: pivotColumnAxis?.label ?? 'Columns',yAxisLabel: pivotRowAxis?.label ?? 'Rows',},diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsxindex 7dcb334ff788..2d1fdea09be8 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIDataPane.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { IconCalendar, IconDatabase } from '@posthog/icons'+import { IconCalendar, IconDatabase, IconPlus } from '@posthog/icons'import { LemonButton, LemonInput, LemonSearchableSelect, Spinner } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'@@ -106,7 +106,7 @@ export function BIDataPane(): JSX.Element {filteredDataPaneFields,selectableDataSources,} = useValues(biEditorLogic)- const { hydrateTableFields, setDataPaneSearch, setDataSource } = useActions(biEditorLogic)+ const { editCalculatedMeasure, hydrateTableFields, setDataPaneSearch, setDataSource } = useActions(biEditorLogic)const { setDatabaseTreeCollapsed } = useActions(editorSizingLogic)const { locateTable } = useActions(queryDatabaseLogic)@@ -223,6 +223,19 @@ export function BIDataPane(): JSX.Element {</>)}</div>+ <div className="border-t p-2">+ <LemonButton+ icon={<IconPlus />}+ size="small"+ fullWidth+ type="secondary"+ onClick={() => editCalculatedMeasure()}+ disabledReason={!config.source ? 'Select a data source first' : undefined}+ data-attr="bi-editor-add-calculated-measure"+ >+ Add calculated measure+ </LemonButton>+ </div></div>)}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFieldPill.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFieldPill.tsxindex 68374e28ef1a..ba498f721f02 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFieldPill.tsx+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFieldPill.tsx@@ -30,6 +30,7 @@ export function BIFieldPill({const { config, activeExpressionEditorId, activeExpressionEditorTarget, sortOptions } = useValues(biEditorLogic)const {addFieldToShelf,+ editCalculatedMeasure,moveFieldToShelf,removeFieldFromShelf,setActiveExpressionEditorId,@@ -47,6 +48,7 @@ export function BIFieldPill({}const isMeasure = shelf === 'values'+ const isCalculatedMeasure = value?.aggregation === 'custom' && !!value.labelconst occurrence = isMeasure? config.values.slice(0, index).filter((previous) => previous.field.id === field.id).length: 0@@ -60,7 +62,7 @@ export function BIFieldPill({const incomplete = value?.aggregation === 'custom' ? !value.customExpression?.trim() : !field.expression.trim()const items: LemonMenuItems = [- isMeasure && value+ isMeasure && value && !isCalculatedMeasure? {title: 'Measure',items: AGGREGATION_OPTIONS.map((option) => ({@@ -91,9 +93,9 @@ export function BIFieldPill({: null,{items: [- { label: 'Edit field expression', onClick: () => setEditing('field') },+ !isCalculatedMeasure ? { label: 'Edit field expression', onClick: () => setEditing('field') } : null,value?.aggregation === 'custom'- ? { label: 'Edit SQL aggregation', onClick: () => setEditing('aggregation') }+ ? { label: 'Edit calculated measure', onClick: () => editCalculatedMeasure(index) }: null,sortKey? {@@ -114,7 +116,11 @@ export function BIFieldPill({{items: [isMeasure- ? { label: 'Convert to dimension', onClick: () => moveFieldToShelf('values', index, 'rows') }+ ? {+ label: 'Convert to dimension',+ disabledReason: isCalculatedMeasure ? 'Calculated measures aggregate each group' : undefined,+ onClick: () => moveFieldToShelf('values', index, 'rows'),+ }: { label: 'Convert to measure', onClick: () => moveFieldToShelf(shelf, index, 'values') },!isMeasure? {@@ -122,7 +128,11 @@ export function BIFieldPill({onClick: () => moveFieldToShelf(shelf, index, otherDimensionShelf),}: null,- { label: 'Add to filters', onClick: () => addFieldToShelf(field, 'filters') },+ {+ label: 'Add to filters',+ disabledReason: isCalculatedMeasure ? 'Filters apply before calculated measures' : undefined,+ onClick: () => addFieldToShelf(field, 'filters'),+ },],},{diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 0670b66a77a6..e7d7bb091ac7 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -2549,6 +2549,23 @@ describe('sqlEditorLogic', () => {biLogic.unmount()})+ it('ignores hydration and status from a different connection', async () => {+ await expectLogic(databaseLogic).toFinishAllListeners()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ databaseLogic.actions.hydrateTableFieldsFailure(['events'])+ await expectLogic(databaseLogic, () =>+ biLogic.actions.restoreState({+ editorView: BIEditorView.BI,+ config: { ...config, source: { table: 'events', connectionId: 'other-connection' } },+ })+ ).toNotHaveDispatchedActions(['hydrateTableFields'])+ expect(biLogic.values.dataPaneFieldsError).toBe(false)+ databaseLogic.actions.hydrateTableFieldsStart(['events'])+ expect(biLogic.values.dataPaneFieldsLoading).toBe(false)+ biLogic.unmount()+ })+it('hydrates fields when the schema arrives after restoring a worksheet', async () => {await expectLogic(databaseLogic).toFinishAllListeners()const biLogic = biEditorLogic({ tabId: TAB_ID })@@ -2591,6 +2608,53 @@ describe('sqlEditorLogic', () => {biLogic.unmount()})+ it('creates and edits a calculated measure without applying canceled drafts or losing its sort', () => {+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()+ biLogic.actions.restoreState({ editorView: BIEditorView.BI, config })+ biLogic.actions.setAutoUpdate(false)+ biLogic.actions.editCalculatedMeasure()+ biLogic.actions.setCalculatedMeasureDraft({+ index: null,+ name: 'ARPU',+ expression: 'sum(revenue) / nullIf(count(DISTINCT user_id), 0)',+ })+ biLogic.actions.updateTab({+ ...biLogic.values.activeTab!,+ biEditorState: { editorView: BIEditorView.BI, config },+ })+ expect(biLogic.values.calculatedMeasureDraft?.name).toBe('ARPU')+ expect(biLogic.values.config.values).toEqual([])+ biLogic.actions.saveCalculatedMeasure()+ expect(biLogic.values.calculatedMeasureDraft).toBeNull()+ expect(biLogic.values.generatedQuery?.query).toContain(+ 'sum(revenue) / nullIf(count(DISTINCT user_id), 0) AS ARPU'+ )+ const value = biLogic.values.config.values[0]+ biLogic.actions.setSort({ key: `values:${value.field.id}`, direction: 'asc' })+ biLogic.actions.editCalculatedMeasure(0)+ biLogic.actions.setCalculatedMeasureDraft({ index: 0, name: 'Canceled name', expression: 'avg(revenue)' })+ biLogic.actions.setCalculatedMeasureDraft(null)+ expect(biLogic.values.config.values[0]).toEqual(value)+ biLogic.actions.editCalculatedMeasure(0)+ expect(biLogic.values.calculatedMeasureDraft?.name).toBe('ARPU')+ biLogic.actions.setCalculatedMeasureDraft({ index: 0, name: 'Average revenue', expression: 'avg(revenue)' })+ biLogic.actions.saveCalculatedMeasure()+ expect(biLogic.values.config.values).toHaveLength(1)+ expect(biLogic.values.config.values[0].field.id).toBe(value.field.id)+ expect(biLogic.values.generatedQuery?.query).toContain('avg(revenue) AS "Average revenue"')+ expect(biLogic.values.generatedQuery?.query).toContain('ORDER BY\n "Average revenue" ASC')+ biLogic.actions.moveFieldToShelf('values', 0, 'filters')+ expect(biLogic.values.config.values).toHaveLength(1)+ expect(biLogic.values.config.filters).toEqual(config.filters)+ biLogic.actions.editCalculatedMeasure(0)+ biLogic.actions.setDataSource({ table: 'other_table' })+ expect(biLogic.values.calculatedMeasureDraft).toBeNull()+ biLogic.actions.saveCalculatedMeasure()+ expect(biLogic.values.config.values).toEqual([])+ biLogic.unmount()+ })+it('keeps field labels consistent with edited expressions', () => {const biLogic = biEditorLogic({ tabId: TAB_ID })biLogic.mount()diff --git a/products/data_warehouse/frontend/bi/BICalculatedMeasureModal.tsx b/products/data_warehouse/frontend/bi/BICalculatedMeasureModal.tsxnew file mode 100644index 000000000000..083d2c656010--- /dev/null+++ b/products/data_warehouse/frontend/bi/BICalculatedMeasureModal.tsx@@ -0,0 +1,91 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonInput, LemonLabel, LemonModal } from '@posthog/lemon-ui'++import { CodeEditorInline } from 'lib/monaco/CodeEditorInline'+import { biEditorLogic } from 'scenes/data-warehouse/editor/bi/biEditorLogic'++import { NodeKind } from '~/queries/schema/schema-general'+import { escapeDottedHogQLIdentifier } from '~/queries/utils'++export function BICalculatedMeasureModal(): JSX.Element | null {+ const { calculatedMeasureDraft: draft, config } = useValues(biEditorLogic)+ const { setCalculatedMeasureDraft, saveCalculatedMeasure } = useActions(biEditorLogic)++ if (!draft || !config.source) {+ return null+ }++ return (+ <LemonModal+ isOpen+ title={draft.index === null ? 'Add calculated measure' : 'Edit calculated measure'}+ onClose={() => setCalculatedMeasureDraft(null)}+ width="36rem"+ data-attr="bi-calculated-measure-modal"+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setCalculatedMeasureDraft(null)}>+ Cancel+ </LemonButton>+ <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+ }+ data-attr="bi-calculated-measure-save"+ >+ {draft.index === null ? 'Add measure' : 'Save measure'}+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ <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"+ autoFocus+ data-attr="bi-calculated-measure-name"+ />+ </div>+ <div className="flex flex-col gap-2">+ <LemonLabel>Formula</LemonLabel>+ <CodeEditorInline+ value={draft.expression}+ onChange={(expression) => setCalculatedMeasureDraft({ ...draft, expression: expression ?? '' })}+ language="hogQLExpr"+ minHeight="100px"+ options={{ ariaLabel: 'Calculated measure formula' }}+ sourceQuery={{+ kind: NodeKind.HogQLQuery,+ query: `SELECT * FROM ${escapeDottedHogQLIdentifier(config.source.table)}`,+ connectionId: config.source.connectionId,+ }}+ onPressCmdEnter={saveCalculatedMeasure}+ 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.+ </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>+ </div>+ </div>+ </LemonModal>+ )+}