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.

fix(data-warehouse): correct bi chart breakdowns and date bounds (#111781)

Marius Andra840b13a69a67
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
index 0ebf19c29a3d..f50e0ee088bd 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -378,9 +378,18 @@ describe('sqlLineGraphAdapter', () => {
expect(series.fill).toBeUndefined()
})
- it('keys breakdown series by breakdown value', () => {
- const [series] = buildSeries([breakdownSeries('chrome', [1])], ChartDisplayType.ActionsLineGraph)
- expect(series.key).toBe('chrome')
+ it('keeps measures with the same breakdown value distinct, including their trend lines', () => {
+ const yData = [
+ { ...breakdownSeries('chrome', [1], { display: { trendLine: true } }), name: 'count - chrome' },
+ { ...breakdownSeries('chrome', [2]), name: 'revenue - chrome' },
+ ]
+ const series = buildSeries(yData, ChartDisplayType.ActionsStackedBar)
+ expect(new Set(series.map(({ key }) => key)).size).toBe(2)
+ expect(Object.fromEntries(series.map(({ key, data }) => [key, data]))).toEqual({
+ '["count - chrome","chrome"]': [1],
+ '["revenue - chrome","chrome"]': [2],
+ })
+ expect(buildTrendLineConfigs(yData)).toEqual([{ seriesKey: series[0].key, kind: 'linear' }])
})
it('honors a custom display label, falling back to the column name', () => {
@@ -456,7 +465,7 @@ describe('sqlLineGraphAdapter', () => {
[
'breakdown trend lines keyed by breakdown value',
[breakdownSeries('chrome', [1], { display: { trendLine: true } })],
- [{ seriesKey: 'chrome', kind: 'linear' }],
+ [{ seriesKey: '["chrome","chrome"]', kind: 'linear' }],
],
])('builds %s', (_name, ySeriesData, expected) => {
expect(buildTrendLineConfigs(ySeriesData)).toEqual(expected)
@@ -471,8 +480,8 @@ describe('sqlLineGraphAdapter', () => {
const seriesKeys = buildSeries(yData, ChartDisplayType.ActionsLineGraph).map((s) => s.key)
const trendLineKeys = buildTrendLineConfigs(yData).map((t) => t.seriesKey)
// Both derive from getSeriesKey on the same array, so the trend lines are the opt-in subset.
- expect(seriesKeys).toEqual(['a-0', 'b-1', 'chrome'])
- expect(trendLineKeys).toEqual(['b-1', 'chrome'])
+ expect(seriesKeys).toEqual(['a-0', 'b-1', '["chrome","chrome"]'])
+ expect(trendLineKeys).toEqual(['b-1', '["chrome","chrome"]'])
})
it('uses array-position indexing, so keys stay aligned with buildSeries however the cap slices', () => {
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index 42465acf23cd..5098135c5519 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -95,7 +95,7 @@ const getSeriesLabel = (series: SqlLineYSeries): string =>
series.settings?.display?.label || ('name' in series ? series.name : series.column.name)
const getSeriesKey = (series: SqlLineYSeries, index: number): string =>
- 'breakdownValue' in series ? series.breakdownValue : `${series.column.name}-${index}`
+ 'breakdownValue' in series ? JSON.stringify([series.name, series.breakdownValue]) : `${series.column.name}-${index}`
/** Shares {@link getSeriesKey} with {@link buildSeries} so each trend line's `seriesKey` matches its source series. */
export function buildTrendLineConfigs(ySeriesData: SqlLineYSeries[] | null | undefined): TrendLineConfig[] {
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
index 65b95f5951d5..f9716573740a 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
@@ -964,20 +964,28 @@ export const biEditorLogic = kea<biEditorLogicType>([
const editorLogic = sqlEditorLogic({ tabId: logicProps.tabId })
const sourceQuery = editorLogic.values.sourceQuery
const generatedChartSettings = values.generatedQuery.node.chartSettings
+ const chartSettings = { ...sourceQuery.chartSettings }
+ if (chartSettings.seriesBreakdownColumn?.startsWith('bi_')) {
+ delete chartSettings.xAxis
+ delete chartSettings.xAxisLabel
+ delete chartSettings.yAxis
+ delete chartSettings.seriesBreakdownColumn
+ delete chartSettings.showLegend
+ }
editorLogic.actions.setQueryInput(values.generatedQuery.query)
editorLogic.actions.setSourceQuery({
...sourceQuery,
...values.generatedQuery.node,
chartSettings: generatedChartSettings
? {
- ...sourceQuery.chartSettings,
+ ...chartSettings,
...generatedChartSettings,
heatmap: {
...sourceQuery.chartSettings?.heatmap,
...generatedChartSettings.heatmap,
},
}
- : sourceQuery.chartSettings,
+ : chartSettings,
source: {
...sourceQuery.source,
...values.generatedQuery.node.source,
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
index e8aef12afe1b..5f5c3a48c70e 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
@@ -240,6 +240,68 @@ describe('BI editor query generation', () => {
expect(result?.query).toContain('count(*) AS count')
})
+ it.each([
+ { chartType: ChartDisplayType.ActionsBar, rows: [], columns: [timestampField, browserField], values: [] },
+ { chartType: ChartDisplayType.ActionsStackedBar, rows: [browserField], columns: [timestampField], values: [] },
+ { chartType: ChartDisplayType.ActionsLineGraph, rows: [timestampField, browserField], columns: [], values: [] },
+ { chartType: ChartDisplayType.ActionsAreaGraph, rows: [timestampField], columns: [browserField], values: [] },
+ {
+ chartType: ChartDisplayType.Auto,
+ rows: [browserField],
+ columns: [timestampField],
+ values: [{ field: revenueField, aggregation: 'sum' as const }],
+ },
+ ])('maps two dimensions to an axis and a breakdown for $chartType', ({ chartType, rows, columns, values }) => {
+ const result = buildBIQuery({
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ chartType,
+ rows: rows.map((field) => (field === timestampField ? { ...field, dateBucket: 'day' } : field)),
+ columns: columns.map((field) => (field === timestampField ? { ...field, dateBucket: 'day' } : field)),
+ values,
+ })!
+
+ const settings = result.node.chartSettings!
+ expect(result.query).toContain(`toStartOfDay(timestamp) AS ${settings.xAxis!.column}`)
+ expect(result.query).toContain(`properties.$browser AS ${settings.seriesBreakdownColumn}`)
+ expect(settings.xAxis!.column).not.toBe(settings.seriesBreakdownColumn)
+ expect(settings.yAxis).toEqual([{ column: values.length ? 'sum_revenue' : 'count' }])
+ expect(result.node.display).toBe(chartType)
+ })
+
+ it('keeps a numeric column dimension on the x-axis instead of treating it as a measure', () => {
+ const result = buildBIQuery({
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsStackedBar,
+ rows: [browserField],
+ columns: [revenueField],
+ })!
+
+ expect(result.node.chartSettings).toEqual({
+ xAxis: { column: 'bi_column_revenue' },
+ xAxisLabel: 'revenue',
+ yAxis: [{ column: 'count' }],
+ seriesBreakdownColumn: 'bi_row_browser',
+ showLegend: true,
+ })
+ expect(result.query).toContain('properties.revenue AS bi_column_revenue')
+ })
+
+ it.each(['rows', 'columns'] as const)('disambiguates colliding dimension aliases on %s', (shelf) => {
+ const result = buildBIQuery({
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsStackedBar,
+ [shelf]: [{ ...eventField, name: 'browser_2' }, browserField],
+ })!
+
+ const { xAxis, seriesBreakdownColumn } = result.node.chartSettings!
+ expect(xAxis!.column).not.toBe(seriesBreakdownColumn)
+ expect(result.query).toContain(`event AS ${xAxis!.column}`)
+ 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) => {
@@ -424,18 +486,18 @@ describe('BI editor query generation', () => {
expect(createDefaultDateFilter(source)).toBeNull()
})
- it('generates a relative date condition for the last 7 days', () => {
+ it('bounds the default last 7 days condition at the current time', () => {
const result = buildBIQuery({
source: { table: 'events' },
chartType: ChartDisplayType.Auto,
rows: [],
columns: [],
values: [],
- filters: [{ field: timestampField, operator: 'last_7_days', value: '' }],
+ filters: [createDefaultDateFilter({ table: 'events' })!],
limit: 100,
})
- expect(result?.query).toContain('timestamp >= now() - INTERVAL 7 DAY')
+ expect(result?.query).toContain('(timestamp >= now() - INTERVAL 7 DAY AND timestamp < now())')
})
test.each([
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
index 3f9277598967..f31751edb1da 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
@@ -733,7 +733,7 @@ function filterExpression(filter: BIFilter): string | null {
return `${field} IS NULL`
}
if (filter.operator === 'last_7_days') {
- return `${field} >= now() - INTERVAL 7 DAY`
+ return `(${field} >= now() - INTERVAL 7 DAY AND ${field} < now())`
}
// Strip leading zeroes so decimal input cannot become an octal HogQL literal.
const literal = (value: string): string =>
@@ -825,12 +825,15 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {
...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 usedAliases = new Set(['bi_rows', 'bi_columns'])
+ for (const dimension of [...rowDimensions, ...columnDimensions]) {
+ const preferred = dimension.alias
+ let suffix = 2
+ while (usedAliases.has(dimension.alias)) {
+ dimension.alias = `${preferred}_${suffix++}`
+ }
+ usedAliases.add(dimension.alias)
+ }
const reservedAliases = new Set(configuredValues.map(({ value }, index) => aggregationAlias(value, index)))
configuredValues.forEach((configuredValue, index) => {
const preferred = aggregationAlias(configuredValue.value, index)
@@ -992,13 +995,24 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
const dimensions = [...rowDimensions, ...columnDimensions]
const dimensionExpressions = dimensions.map(({ field }) => fieldExpression(field))
const isPivotTable = config.chartType === ChartDisplayType.TwoDimensionalHeatmap
+ const hasSeriesBreakdown =
+ dimensions.length === 2 &&
+ [
+ ChartDisplayType.Auto,
+ ChartDisplayType.ActionsBar,
+ ChartDisplayType.ActionsStackedBar,
+ ChartDisplayType.ActionsLineGraph,
+ ChartDisplayType.ActionsAreaGraph,
+ ].includes(config.chartType)
const pivotRowAxis = isPivotTable ? pivotAxis('row', rowDimensions) : null
const pivotColumnAxis = isPivotTable ? pivotAxis('column', columnDimensions) : null
const dimensionSelectExpressions = isPivotTable
? [pivotRowAxis, pivotColumnAxis]
.filter((axis): axis is BIPivotAxis => axis !== null)
.map(({ alias, expression }) => `${expression} AS ${alias}`)
- : dimensionExpressions
+ : dimensions.map(({ field, alias }) =>
+ hasSeriesBreakdown ? `${fieldExpression(field)} AS ${alias}` : fieldExpression(field)
+ )
const valueExpressions =
configuredValues.length > 0
? configuredValues.map(
@@ -1036,6 +1050,23 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
const query = queryParts.join('\n')
+ const chartDimensions = [...columnDimensions, ...rowDimensions]
+ const xDimension = chartDimensions.find(({ field }) => isDateTimeBIField(field)) ?? chartDimensions[0]
+ const breakdownDimension = chartDimensions.find((dimension) => dimension !== xDimension)
+ const seriesSettings =
+ hasSeriesBreakdown && xDimension && breakdownDimension
+ ? {
+ xAxis: { column: xDimension.alias },
+ xAxisLabel: getBIFieldPillLabel(xDimension.field),
+ yAxis:
+ configuredValues.length > 0
+ ? configuredValues.map(({ alias }) => ({ column: alias }))
+ : [{ column: 'count' }],
+ seriesBreakdownColumn: breakdownDimension.alias,
+ showLegend: true,
+ }
+ : undefined
+
const pivotTableSettings = isPivotTable
? {
heatmap: {
@@ -1058,7 +1089,7 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
connectionId: config.source.connectionId,
},
display: config.chartType,
- ...(pivotTableSettings ? { chartSettings: pivotTableSettings } : {}),
+ ...(pivotTableSettings || seriesSettings ? { chartSettings: pivotTableSettings ?? seriesSettings } : {}),
},
}
}
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 133d049a764c..0050ed9656fb 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -2361,6 +2361,37 @@ describe('sqlEditorLogic', () => {
sort_direction: null,
}
+ it('updates the chart breakdown when dimensions move between shelves or are removed', async () => {
+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
+ logic.mount()
+ const biLogic = biEditorLogic({ tabId: TAB_ID })
+ biLogic.mount()
+ biLogic.actions.setAutoUpdate(false)
+ biLogic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: { ...config, rows: [], columns: [timestampField, eventField] },
+ })
+ biLogic.actions.syncGeneratedQuery()
+
+ expect(logic.values.sourceQuery.chartSettings).toMatchObject({
+ xAxis: { column: 'bi_column_timestamp' },
+ seriesBreakdownColumn: 'bi_column_event_2',
+ yAxis: [{ column: 'count' }],
+ })
+
+ biLogic.actions.moveFieldToShelf('columns', 1, 'rows')
+ expect(logic.values.sourceQuery.chartSettings).toMatchObject({
+ xAxis: { column: 'bi_column_timestamp' },
+ seriesBreakdownColumn: 'bi_row_event',
+ })
+
+ biLogic.actions.removeFieldFromShelf('rows', 0)
+ expect(logic.values.sourceQuery.chartSettings?.seriesBreakdownColumn).toBeUndefined()
+ expect(logic.values.sourceQuery.chartSettings?.xAxis).toBeUndefined()
+ expect(logic.values.sourceQuery.chartSettings?.showLegend).toBeUndefined()
+ biLogic.unmount()
+ })
+
it('captures BI mode selection and query runs without query contents', async () => {
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SQL_EDITOR_BI_MODE], {
[FEATURE_FLAGS.SQL_EDITOR_BI_MODE]: true,
@@ -2703,7 +2734,7 @@ describe('sqlEditorLogic', () => {
})
test.each(['ready', 'failed', 'cancelled', 'missing'] as const)(
- 'handles chart-only changes with %s query results and runs changed pivot SQL',
+ 'handles chart-only changes with %s query results and runs changed table SQL',
async (resultState) => {
logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
logic.mount()
@@ -2733,11 +2764,11 @@ describe('sqlEditorLogic', () => {
jest.useFakeTimers()
try {
biLogic.actions.setAutoUpdate(true)
- biLogic.actions.setChartType(ChartDisplayType.ActionsTable)
+ biLogic.actions.setChartType(ChartDisplayType.ActionsStackedBar)
await jest.advanceTimersByTimeAsync(500)
- expect(logic.values.sourceQuery.display).toBe(ChartDisplayType.ActionsTable)
+ expect(logic.values.sourceQuery.display).toBe(ChartDisplayType.ActionsStackedBar)
expect(runQuery).toHaveBeenCalledTimes(resultState === 'ready' ? 0 : 1)
- biLogic.actions.setChartType(ChartDisplayType.TwoDimensionalHeatmap)
+ biLogic.actions.setChartType(ChartDisplayType.ActionsTable)
await jest.advanceTimersByTimeAsync(500)
expect(runQuery).toHaveBeenCalledTimes(resultState === 'ready' ? 1 : 2)
} finally {