: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
fix(bi): preserve query result dimension identity (#117111)
Marius Andrae2a2dd597c79
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 084b0a78b55c..1f185bad0fb0 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -38,7 +38,7 @@ Choose a connection in the **Data** panel, then select a table below it. **Run**Single-value filters distinguish selecting **(empty string)** from clearing the input: the former matches an empty value, while the latter removes the condition.-Date dimensions sort oldest first by default, including in tables; explicit sorts still take precedence. Time charts show years centered below their date ticks. Clicking a bar opens the drill-down options for that result.+Date dimensions sort oldest first by default, including in tables; explicit sorts still take precedence. Generated date dimensions retain their result-column identity, including expressions over column names containing spaces. Time charts show years centered below their date ticks. Clicking a bar opens the drill-down options for that result.**Auto update** is off by default and remembers your choice. Selecting a table leaves a blank worksheet, even with auto-update enabled. The blank worksheet offers **Start with daily row count** when a date field is available, or **Start with row count** otherwise. The suggestion adds fields only when clicked and respects auto-update. Identifier fields such as `person_id`, `distinct_id`, and `user_id` appear as measures and default to Count; their shelf menu can convert them to dimensions or change the aggregation. A worksheet with dimensions and no selected measure shows **Count of rows** on its shelf and value axis. Turning auto-update off keeps the current result; **Run** applies pending changes.@@ -314,6 +314,8 @@ You'll need to install MS SQL drivers for the PostHog app to connect to a MS SQLsymbol not found in flat namespace '_bcp_batch'```+Repeated dimension pills use distinct result columns so their chart and table bindings stay unambiguous. Generated dimension aliases avoid source identifiers used by measures and filters. Expressions containing percent signs or matching reserved names use supported generated aliases while keeping their original calculation.+BI chart settings preserve custom scatter axes and implicit count formatting. Numeric date parts can be used as scatter axes. Switching to a box plot initializes statistic mappings from matching result column names. Generated axis labels follow field renames, while custom axis labels remain unchanged.## Connected fields in BI modediff --git a/products/business_intelligence/frontend/biEditorLogic.test.ts b/products/business_intelligence/frontend/biEditorLogic.test.tsindex 5328f66119a8..1d320a479808 100644--- a/products/business_intelligence/frontend/biEditorLogic.test.ts+++ b/products/business_intelligence/frontend/biEditorLogic.test.ts@@ -625,7 +625,7 @@ describe('biEditorLogic', () => {biLogic.actions.setAutoUpdate(false)biLogic.actions.setFieldExpression('rows', 0, 'distinct_id')expect(getBIFieldPillLabel(biLogic.values.config.rows[0])).toBe('distinct_id')- expect(biLogic.values.generatedQuery?.query).toContain('SELECT\n distinct_id,')+ expect(biLogic.values.generatedQuery?.query).toContain('SELECT\n distinct_id AS distinct_id,')biLogic.unmount()})})diff --git a/products/business_intelligence/frontend/biEditorTypes.test.ts b/products/business_intelligence/frontend/biEditorTypes.test.tsindex 2a97e477de05..474e82ef0ad2 100644--- a/products/business_intelligence/frontend/biEditorTypes.test.ts+++ b/products/business_intelligence/frontend/biEditorTypes.test.ts@@ -11,6 +11,7 @@ import {defaultAggregationForField,getBIDataSourceKey,getBIChartFit,+ getBIResultDimensions,getBIDropTarget,getBIFieldId,getBISortOptions,@@ -63,6 +64,97 @@ const countryField: BIField = {}describe('BI editor query generation', () => {+ it.each(+ [ChartDisplayType.ActionsTable, ChartDisplayType.ActionsLineGraph, ChartDisplayType.ScatterPlot]+ .flatMap((chartType) => [+ { chartType, name: 'repeated dimensions', rows: [eventField, eventField, eventField] },+ {+ chartType,+ name: 'an expression containing a percent sign',+ rows: [{ ...eventField, expression: "if(event LIKE 'page%', 'page', 'other')" }],+ },+ ])+ .concat(+ ['true', 'FALSE', 'null', 'team_id'].map((expression) => ({+ chartType: ChartDisplayType.ActionsTable,+ name: `the reserved alias ${expression}`,+ rows: [{ ...eventField, expression }],+ }))+ )+ )('binds $name to supported distinct result columns in $chartType', ({ chartType, rows }) => {+ const config = {+ ...DEFAULT_BI_CONFIG,+ source: eventField.source,+ chartType,+ rows,+ }+ const result = buildBIQuery(config)!+ const columns = getBIResultDimensions(config).map(({ column }) => column)+ expect(new Set(columns).size).toBe(rows.length)+ expect(result.query).toContain(`GROUP BY\n ${columns.join(',\n ')}`)+ for (const [index, column] of columns.entries()) {+ expect(column).not.toContain('%')+ expect(['true', 'false', 'null', 'team_id']).not.toContain(column.toLowerCase())+ expect(result.query).toContain(`${rows[index].expression} AS ${column}`)+ expect(result.node.tableSettings?.columns).toContainEqual(expect.objectContaining({ column }))+ }+ if (chartType !== ChartDisplayType.ScatterPlot) {+ expect(result.node.chartSettings?.xAxis?.column).toBe(columns[0])+ }+ const comparison = buildBIQuery({+ ...config,+ chartType: ChartDisplayType.ActionsTable,+ dateRange: { date_from: 'mStart' },+ compareFilter: { compare: true },+ })!+ expect(comparison.query).toContain(`GROUP BY ${[...columns, 'bi_comparison'].join(', ')}`)+ })++ it.each(['measure', 'custom measure', 'filter', 'custom filter'] as const)(+ 'keeps generated dimension aliases from shadowing a source identifier in a %s',+ (reference) => {+ const sourceField = { ...revenueField, name: 'bi_row_event', expression: 'bi_row_event' }+ const config: BIConfig = {+ ...DEFAULT_BI_CONFIG,+ source: eventField.source,+ rows: [eventField, eventField],+ values: reference.includes('measure')+ ? [+ reference === 'measure'+ ? { field: sourceField, aggregation: 'sum' }+ : {+ field: sourceField,+ aggregation: 'custom',+ customExpression: 'sum(bi_row_event)',+ },+ ]+ : [],+ filters: reference.includes('filter')+ ? [+ reference === 'filter'+ ? { field: sourceField, operator: 'greater_than', value: '0' }+ : {+ field: sourceField,+ operator: 'custom',+ value: '',+ customExpression: 'bi_row_event > 0',+ },+ ]+ : [],+ }+ const result = buildBIQuery(config)!+ const columns = getBIResultDimensions(config).map(({ column }) => column)+ expect(new Set(columns).size).toBe(2)+ expect(columns).not.toContain('bi_row_event')+ expect(result.query).not.toMatch(/event AS bi_row_event[,\n]/)+ expect(result.query).toContain(reference.includes('measure') ? 'sum(bi_row_event)' : 'bi_row_event > 0')+ for (const column of columns) {+ expect(result.query).toContain(`event AS ${column}`)+ expect(result.node.tableSettings?.columns).toContainEqual(expect.objectContaining({ column }))+ }+ }+ )+test.each(['month', 'quarter', 'day_of_week'] as const)('uses numeric %s date parts for scatter axes',(datePart) => {@@ -304,7 +396,7 @@ describe('BI editor query generation', () => {it('builds a visualization node with dimensions, aggregations, and filters', () => {const expectedQuery = ['SELECT',- ' event,',+ ' event AS event,',' sum(properties.revenue) AS sum_revenue','FROM events','WHERE',@@ -451,22 +543,32 @@ describe('BI editor query generation', () => {expect(result.query).toContain(`properties.$browser AS ${seriesBreakdownColumn}`)})- it.each([100, 1000, 10000, 50000] as const)(- 'maps every BI row and column dimension to pivot table axes with limit %i',- (limit) => {+ it.each([+ ...([100, 1000, 10000, 50000] as const).map((limit) => ({ limit, repeated: false })),+ { limit: 100 as const, repeated: true },+ ])(+ 'maps every BI row and column dimension to pivot table axes with limit $limit (repeated: $repeated)',+ ({ limit, repeated }) => {+ const secondRow = repeated ? eventField : timestampField+ const secondColumn = repeated ? browserField : countryFieldconst result = buildBIQuery({source: { table: 'events' },chartType: ChartDisplayType.TwoDimensionalHeatmap,- rows: [eventField, timestampField],- columns: [browserField, countryField],+ rows: [eventField, secondRow],+ columns: [browserField, secondColumn],values: [{ field: revenueField, aggregation: 'sum' }],filters: [],limit,})- expect(result?.query).toContain('event AS bi_row_event, timestamp AS bi_row_timestamp_2')+ expect(result?.query).toContain(+ `event AS bi_row_event, ${secondRow.expression} AS bi_row_${secondRow.name}_2`+ )expect(result?.query).toContain('properties.$browser AS bi_column_browser')- expect(result?.query).toContain('properties.$geoip_country_name AS bi_column_country_2')+ expect(result?.query).toContain(`${secondColumn.expression} AS bi_column_${secondColumn.name}_2`)+ expect(result?.query).toContain(+ `GROUP BY GROUPING SETS ((bi_row_event, bi_row_${secondRow.name}_2, bi_column_browser, bi_column_${secondColumn.name}_2)`+ )expect(result?.query).toMatch(/toJSONString\(tuple\(.*\)\) AS bi_rows/)expect(result?.query).toMatch(/toJSONString\(tuple\(.*\)\) AS bi_columns/)expect(result?.query).toContain(`LIMIT ${limit}`)@@ -475,8 +577,8 @@ describe('BI editor query generation', () => {xAxisColumn: 'bi_columns',yAxisColumn: 'bi_rows',valueColumn: 'sum_revenue',- xAxisLabel: 'browser / country',- yAxisLabel: 'event / timestamp',+ xAxisLabel: `browser / ${secondColumn.name}`,+ yAxisLabel: `event / ${secondRow.name}`,},})}@@ -519,7 +621,7 @@ describe('BI editor query generation', () => {expect(result?.query).toEqual(['SELECT',- ' event,',+ ' event AS event,',' count(*) AS count','FROM events','WHERE',@@ -678,6 +780,7 @@ describe('BI editor query generation', () => {})expect(result?.query).toContain(`${dateBucketFunction}(timestamp)`)+ expect(result?.query).toContain(`${dateBucketFunction}(timestamp) AS "${dateBucketFunction}(timestamp)"`)})test.each([diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.tsindex 744b3c88c1a7..49afc28b8170 100644--- a/products/business_intelligence/frontend/biEditorTypes.ts+++ b/products/business_intelligence/frontend/biEditorTypes.ts@@ -1161,6 +1161,7 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {...columnDimensions.map(({ field }) => fieldExpression(field)),...configuredValues.map(({ expression }) => expression),...config.filters.map((filter) => filter.customExpression || fieldExpression(filter.field)),+ ...(config.dateField ? [fieldExpression(config.dateField)] : []),]const usedAliases = new Set(['bi_rows',@@ -1174,7 +1175,10 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {for (const dimension of [...rowDimensions, ...columnDimensions]) {const preferred = dimension.aliaslet suffix = 2- while (usedAliases.has(dimension.alias)) {+ while (+ usedAliases.has(dimension.alias) ||+ expressions.some((expression) => expression.includes(dimension.alias))+ ) {dimension.alias = `${preferred}_${suffix++}`}usedAliases.add(dimension.alias)@@ -1203,6 +1207,15 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {return { rowDimensions, columnDimensions, configuredValues }}+function needsGeneratedDimensionAliases(dimensions: BIDimension[], hasMeasures: boolean): boolean {+ const expressions = dimensions.map(({ field }) => fieldExpression(field))+ return (+ new Set(expressions).size !== expressions.length ||+ (!hasMeasures && expressions.includes('count')) ||+ expressions.some((expression) => expression.includes('%') || /^(true|false|null|team_id)$/i.test(expression))+ )+}+export function getBIResultDimensions(config: BIConfig): { field: BIField; column: string; position?: number }[] {const { rowDimensions, columnDimensions } = computeBIQueryParts(config)const dimensions = [...rowDimensions, ...columnDimensions]@@ -1216,6 +1229,7 @@ export function getBIResultDimensions(config: BIConfig): { field: BIField; colum)}const aliased =+ needsGeneratedDimensionAliases(dimensions, config.values.length > 0) ||hasBIAnalysis(config) ||config.compareFilter?.compare ||(dimensions.length === 2 &&@@ -1424,6 +1438,7 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuerconst { rowDimensions, columnDimensions, configuredValues } = computeBIQueryParts(config)const dimensions = [...rowDimensions, ...columnDimensions]+ const generatedDimensionAliases = needsGeneratedDimensionAliases(dimensions, configuredValues.length > 0)const comparing = !!config.compareFilter?.compareconst dimensionExpressions = dimensions.map(({ field }) => fieldExpression(field))const isPivotTable = config.chartType === ChartDisplayType.TwoDimensionalHeatmap@@ -1444,9 +1459,9 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer.filter((axis): axis is BIPivotAxis => axis !== null).map(({ alias, expression }) => `${expression} AS ${alias}`): dimensions.map(({ field, alias }) =>- hasSeriesBreakdown || comparing || hasBIAnalysis(config)+ hasSeriesBreakdown || comparing || hasBIAnalysis(config) || generatedDimensionAliases? `${fieldExpression(field)} AS ${alias}`- : fieldExpression(field)+ : `${fieldExpression(field)} AS ${escapeRawPropertyAsHogQLIdentifier(fieldExpression(field))}`)const valueExpressions =configuredValues.length > 0@@ -1465,7 +1480,8 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer`WHERE\n ${[getBIFiltersPlaceholder(config), ...filters.map((filter) => `(${filter})`)].join('\n AND ')}`)if (dimensionExpressions.length > 0) {- queryParts.push(`GROUP BY\n ${dimensionExpressions.join(',\n ')}`)+ const grouping = generatedDimensionAliases ? dimensions.map(({ alias }) => alias) : dimensionExpressions+ queryParts.push(`GROUP BY\n ${grouping.join(',\n ')}`)}const orderByExpression = buildOrderByExpression(config, dimensions, configuredValues)@@ -1497,7 +1513,12 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer}: {xAxis: xDimension- ? { column: hasBIAnalysis(config) ? xDimension.alias : fieldExpression(xDimension.field) }+ ? {+ column:+ hasBIAnalysis(config) || generatedDimensionAliases+ ? xDimension.alias+ : fieldExpression(xDimension.field),+ }: undefined,yAxis: configuredValues.length? configuredValues.map(({ alias }) => ({ column: alias }))@@ -1536,7 +1557,11 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer`SELECT\n ${select.join(',\n ')}`,`FROM ${escapePropertyAsHogQLIdentifier(config.source!.table)}`,`WHERE\n ${[previous ? placeholder.replace('{filters', '{filters.previous') : placeholder, ...filters.map((filter) => `(${filter})`)].join('\n AND ')}`,- ...(expressions.length ? [`GROUP BY ${[...expressions, 'bi_comparison'].join(', ')}`] : []),+ ...(expressions.length+ ? [+ `GROUP BY ${[...(generatedDimensionAliases ? dimensions.map(({ alias }) => alias) : expressions), 'bi_comparison'].join(', ')}`,+ ]+ : []),].join('\n')}query = limitBIComparisonQuery({@@ -1704,7 +1729,10 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer.filter((axis): axis is BIPivotAxis => !!axis).map((axis) => axis.alias): dimensions.map((dimension) =>- hasBIAnalysis(config) || comparing || hasSeriesBreakdown+ hasBIAnalysis(config) ||+ comparing ||+ hasSeriesBreakdown ||+ generatedDimensionAliases? dimension.alias: fieldExpression(dimension.field))),@@ -1713,7 +1741,11 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer].map((column) => {const dimension = dimensions.find((dimension) =>- (hasBIAnalysis(config) || comparing || hasSeriesBreakdown || isPivotTable+ (hasBIAnalysis(config) ||+ comparing ||+ hasSeriesBreakdown ||+ generatedDimensionAliases ||+ isPivotTable? dimension.alias: fieldExpression(dimension.field)) === column)