Skip to content

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

feat(sql-editor): add compact worksheet filters and ranges (#111027)

Marius Andra9fd00c022161
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 2db3fd0fff4d..8a8d8b549ce2 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -23,6 +23,24 @@ Cancel discards the draft. Names and formulas persist with the worksheet's BI co
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.
+## Filters in BI mode
+
+Drop a field onto the compact Filters shelf beside or below the data pane. Quick filters on the right
+show the current selection; click a value to edit it, or use the checkbox beside its name to toggle it.
+Wider worksheets show quick filters in two columns. In tight scenes, click a filter pill on the left
+to edit its values and settings. String fields start with
+**Is any of**: select several values, or type a value and press Enter. **Is none of** excludes the
+selected values. An empty selection leaves all values included. Suggestions load when the picker
+opens, respect the other applied filters, and show up to 100 distinct values; additional values can
+always be entered manually.
+
+Use **Between** for numeric or date fields. Both bounds are inclusive, and either can be left empty
+for an open-ended range. Date-time fields include the time. Uncheck **Apply filter** in the editor to temporarily
+ignore a filter without losing its settings. Click the field pill to edit the field expression, date
+part, or custom SQL condition, or to remove the filter. Filter changes respect the worksheet's
+auto-update setting and are preserved with its saved configuration.
+Numeric filters preserve the precision of entered values. Invalid numbers show an error and prevent the worksheet from running until corrected or disabled.
+
## Apple Ads in Marketing analytics
Marketing 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.yml
index b891a7cf6e2f..84ce8797ac5e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9503,13 +9503,21 @@ snapshots:
scenes-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
+ hash: v1.k794b7964.25fd8a22fa490bf3e3e600a984b131b28202b8172e46e1a35e090694dfe63e2f.UBgi2bw3KLPn9F1RDJIVKYgfFlzVDD2yZj4iUPufRVA
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
- hash: v1.k794b7964.b5765e1b7a155becef5d85878017eee5ff92bf0941fa8fb4cb27ca70c7b115a3.MHmkJ7F78j_l_g-WUGNy0sozpFp3MZuQQTkCzMTpE_s
+ hash: v1.k794b7964.66016e766d5d3b78aae28be29d15e9bbf7ebb60b48de6d488eb7b10ea4676afd.wpa1Nkk9kYDByTPyA-MjGrtArnLDfzP4S6zkO34CMfo
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
- hash: v1.k794b7964.c658d01e1ed459e380f64ae18cc893a3bdd4d14d60924691224143b4133d304c.bJ8fJvADbAl-CJHuO6-1i9Ng1abedjo0nuR3uHQ42KM
+ hash: v1.k794b7964.ec7208e3d9f889ee6eccaec6109093fd6ea85b10ad19f1aa4789308197f2608f.IaUpl-X0QQu76brKDTNqjxOXEgO4qro9a3NSFX-n0uw
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
- hash: v1.k794b7964.e6e8b6fc3608d3bd734534aae37eb9a8c3d56f5979791ce904a8cf0e18f11f88.S4-L9C5xAT431duxCiXdzDM4sJw1eJ4URMS5uZnhUMI
+ hash: v1.k794b7964.df08de4b285910a523a4074657beabe516e0132ecd5fe87f988dd9490188f43b.G0eYvWelXNWqVgrwyW0GlLMoUDDhkChYKpjXKwm9IWs
+ scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
+ hash: v1.k794b7964.d18442be26b311eab84c68699e59cb29c8e2c6e70a0442ea7e998b5ceae7d634.K8j9lWp-nB9fGXpZV3l__sgKeGmnwrIKSH892cSTAZk
+ scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
+ hash: v1.k794b7964.7d055020d8b9cdc001efc8b5ca146f2d22e7c916af54b7361f2d8f61d59b940f.11bvglysenXe98m_innE4VvTdCUKMhRuSS62QGmFscM
+ scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
+ hash: v1.k794b7964.3a3d179dc8ec4fed037e1e0737ddad5dea4f828b262e35d07ae5c0dcfec1447d.dqy-xY-ApF2QSGtDMf_HIMrtyrPbFAnhhWHB8cmi4M8
+ scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
+ hash: v1.k794b7964.46ca9e07669ba124d6d051b6b0cf1dbbf30b441533a9eaa064c3492577893e93.KhY5WMXImePUoV5bH-nrNztp1axD08hcOl4kfH-uaYQ
scenes-app-data-warehouse-sql-editor--edited-insight--dark:
hash: v1.k794b7964.94eba9d351ec4c6b649fc4b09f5d4a69fed2995448c0cc1dac5d63d3df0ad20c.U6hnpHxuk9RKFoPU8bc536a9dTuzluwHE0pF4J0nPYc
scenes-app-data-warehouse-sql-editor--edited-insight--light:
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 6d683c161e3a..8a69e6a8b43b 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -429,6 +429,108 @@ export const BICalculatedMeasureEditor: Story = {
},
}
+const BI_QUICK_FILTERS_CONFIG: BIConfig = {
+ ...BI_WORKSHEET_CONFIG,
+ chartType: ChartDisplayType.ActionsTable,
+ columns: [],
+ values: [
+ {
+ field: biEventsField('revenue', 'float'),
+ aggregation: 'custom',
+ label: 'ARPU',
+ customExpression: 'sum(revenue) / nullIf(count(DISTINCT user_id), 0)',
+ },
+ ],
+ filters: [
+ { field: biEventsField('event', 'string'), operator: 'in', value: '', values: ['purchase', 'renewal'] },
+ {
+ field: biEventsField('timestamp', 'datetime'),
+ operator: 'between',
+ value: '2026-06-01 00:00:00',
+ valueTo: '2026-06-07 23:59:59',
+ },
+ ],
+}
+
+export const BIQuickFilters: Story = {
+ ...BIModeWorksheet,
+ parameters: {
+ ...BIModeWorksheet.parameters,
+ pageUrl: `${urls.sqlEditor()}#${new URLSearchParams({ q: buildBIQuery(BI_QUICK_FILTERS_CONFIG)?.query ?? '', mode: 'bi', bi: JSON.stringify(BI_QUICK_FILTERS_CONFIG) })}`,
+ msw: {
+ mocks: {
+ ...BIModeWorksheet.parameters?.msw.mocks,
+ post: {
+ ...BIModeWorksheet.parameters?.msw.mocks.post,
+ '/api/environments/:team_id/query/HogQLQuery/': async ({ request }: { request: Request }) => {
+ const { query } = await request.json()
+ return [
+ 200,
+ query.query.startsWith('SELECT DISTINCT')
+ ? {
+ columns: ['value'],
+ types: ['String'],
+ results: [['purchase'], ['renewal'], ['refund'], ['trial_started']],
+ hasMore: false,
+ }
+ : {
+ columns: ['toStartOfDay(timestamp)', 'ARPU'],
+ types: ['DateTime', 'Float64'],
+ hasMore: false,
+ results: [24, 28, 26, 31, 35, 33, 38].map((value, index) => [
+ `2026-06-0${index + 1} 00:00:00`,
+ value,
+ ]),
+ },
+ ]
+ },
+ },
+ },
+ },
+ },
+}
+
+export const BIQuickFiltersNarrow: Story = {
+ ...BIQuickFilters,
+ parameters: {
+ ...BIQuickFilters.parameters,
+ pageUrl: `${urls.sqlEditor()}#${new URLSearchParams({
+ mode: 'bi',
+ bi: JSON.stringify({
+ ...BI_QUICK_FILTERS_CONFIG,
+ filters: [
+ ...BI_QUICK_FILTERS_CONFIG.filters,
+ {
+ field: biEventsField('properties.region', 'string'),
+ operator: 'in',
+ value: '',
+ values: ['North', 'West'],
+ },
+ {
+ field: biEventsField('properties.device', 'string'),
+ operator: 'in',
+ value: '',
+ values: ['Desktop'],
+ },
+ {
+ field: biEventsField('properties.channel', 'string'),
+ operator: 'not_in',
+ value: '',
+ values: ['Internal'],
+ },
+ { field: biEventsField('revenue', 'float'), operator: 'between', value: '0', valueTo: '1000' },
+ { field: biEventsField('duration_ms', 'integer'), operator: 'less_than', value: '5000' },
+ { field: biEventsField('distinct_id', 'string'), operator: 'is_set', value: '' },
+ ],
+ } satisfies BIConfig),
+ })}`,
+ testOptions: {
+ waitForSelector: '[data-attr="bi-editor-filters-pill"]',
+ viewport: { width: 1050, height: 900 },
+ },
+ },
+}
+
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.tsx
index ac7cdf45fe5d..e30465b1807b 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx
@@ -5,6 +5,7 @@ import { Resizer } from 'lib/components/Resizer/Resizer'
import { IconTableChart } from 'lib/lemon-ui/icons'
import { BICalculatedMeasureModal } from 'products/data_warehouse/frontend/bi/BICalculatedMeasureModal'
+import { BIFilterControl } from 'products/data_warehouse/frontend/bi/BIFilterControl'
import { editorSizingLogic } from '../editorSizingLogic'
import { biEditorLogic } from './biEditorLogic'
@@ -49,7 +50,7 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
<BICalculatedMeasureModal />
<div className="flex min-h-0 flex-1">
<div
- className="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"
+ className="relative flex w-[var(--bi-side-pane-width)] shrink-0 flex-col border-r @5xl/bi-editor:w-[calc(var(--bi-side-pane-width)+10rem)] @5xl/bi-editor:flex-row"
// eslint-disable-next-line react/forbid-dom-props
style={{ '--bi-side-pane-width': `${biSidePaneWidth}px` } as React.CSSProperties}
>
@@ -57,7 +58,7 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
<div ref={biEditorResizerProps.containerRef} className="flex min-h-0 min-w-0 flex-1 flex-col">
<BIDataPane />
</div>
- <div className="flex max-h-[50%] shrink-0 flex-col overflow-y-auto border-t @4xl/bi-editor:max-h-none @4xl/bi-editor:w-48 @4xl/bi-editor:border-l @4xl/bi-editor:border-t-0">
+ <div className="flex max-h-[40%] shrink-0 flex-col overflow-y-auto border-t @5xl/bi-editor:max-h-none @5xl/bi-editor:w-40 @5xl/bi-editor:border-l @5xl/bi-editor:border-t-0">
<BIFiltersCard />
<BIMarksCard />
</div>
@@ -91,9 +92,19 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
</BIShelfStrip>
<div className="flex min-h-0 flex-1 flex-col">{children}</div>
</div>
- {showMeOpen ? (
- <div className="hidden shrink-0 border-l bg-surface-primary @3xl/bi-editor:flex">
- <BIShowMe docked />
+ {showMeOpen || config.filters.length > 0 ? (
+ <div className="hidden w-44 shrink-0 flex-col overflow-y-auto border-l bg-surface-primary @3xl/bi-editor:flex @6xl/bi-editor:w-80">
+ {config.filters.length > 0 && (
+ <section className="border-b p-2" aria-label="Quick filters">
+ <h3 className="mb-2 text-xs font-semibold">Filters</h3>
+ <div className="grid grid-cols-1 items-start gap-x-2 gap-y-2 @6xl/bi-editor:grid-cols-2">
+ {config.filters.map((filter, index) => (
+ <BIFilterControl key={filter.field.id} index={index} />
+ ))}
+ </div>
+ </section>
+ )}
+ {showMeOpen && <BIShowMe docked />}
</div>
) : null}
</div>
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
index 1cacebff4e48..65b95f5951d5 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
@@ -21,6 +21,7 @@ import {
BIEditorState,
BIEditorView,
BIField,
+ BIFilter,
BIFilterOperator,
BIQueryBuildResult,
BIQueryLimit,
@@ -29,6 +30,7 @@ import {
BISortOption,
DEFAULT_BI_CONFIG,
buildBIQuery,
+ changeBIFilterOperator,
createDefaultDateFilter,
defaultAggregationForField,
getBIChartFit,
@@ -127,7 +129,10 @@ function addFieldToConfig(config: BIConfig, field: BIField, shelf: BIShelf): BIC
return {
...sourceConfig,
source,
- filters: [...sourceConfig.filters, { field, operator: 'equals', value: '' }],
+ filters: [
+ ...sourceConfig.filters,
+ { field, operator: field.type === 'string' ? 'in' : 'equals', value: '' },
+ ],
}
}
}
@@ -436,6 +441,13 @@ export interface biEditorLogicActions {
syncGeneratedQuery: () => {
value: true
}
+ updateFilter: (
+ index: number,
+ update: Partial<Pick<BIFilter, 'enabled' | 'values' | 'valueTo'>>
+ ) => {
+ index: number
+ update: Partial<Pick<BIFilter, 'enabled' | 'values' | 'valueTo'>>
+ }
upsertCalculatedMeasure: (draft: BICalculatedMeasureDraft) => {
draft: BICalculatedMeasureDraft
fieldId: string
@@ -539,6 +551,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
setValueAggregation: (index: number, aggregation: BIAggregation) => ({ index, aggregation }),
setFilterOperator: (index: number, operator: BIFilterOperator) => ({ index, operator }),
setFilterValue: (index: number, value: string) => ({ index, value }),
+ updateFilter: (index: number, update: Partial<Pick<BIFilter, 'values' | 'valueTo' | 'enabled'>>) => ({
+ index,
+ update,
+ }),
setLimit: (limit: BIQueryLimit) => ({ limit }),
setSort: (sort: BISort | null) => ({ sort }),
setFieldExpression: (shelf: BIShelf, index: number, expression: string) => ({ shelf, index, expression }),
@@ -663,7 +679,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setFilterOperator: (config, { index, operator }) => ({
...config,
filters: config.filters.map((filter, filterIndex) =>
- filterIndex === index ? { ...filter, operator } : filter
+ filterIndex === index ? changeBIFilterOperator(filter, operator) : filter
),
}),
setFilterValue: (config, { index, value }) => ({
@@ -672,6 +688,12 @@ export const biEditorLogic = kea<biEditorLogicType>([
filterIndex === index ? { ...filter, value } : filter
),
}),
+ updateFilter: (config, { index, update }) => ({
+ ...config,
+ filters: config.filters.map((filter, filterIndex) =>
+ filterIndex === index ? { ...filter, ...update } : filter
+ ),
+ }),
setLimit: (config, { limit }) => normalizeBIConfig({ ...config, limit }),
setSort: (config, { sort }) => normalizeBIConfig({ ...config, sort }),
setFieldExpression: (config, { shelf, index, expression }) =>
@@ -894,6 +916,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setValueAggregation: () => actions.runAfterChange(),
setFilterOperator: () => actions.runAfterChange(),
setFilterValue: () => actions.runAfterChange(),
+ updateFilter: () => actions.runAfterChange(),
setLimit: () => actions.runAfterChange(),
setSort: () => actions.runAfterChange(),
setFieldExpression: () => actions.runAfterChange(),
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorOptions.tsx b/frontend/src/scenes/data-warehouse/editor/bi/biEditorOptions.tsx
index 4b1bf73e90fb..fb2217362ee9 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorOptions.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorOptions.tsx
@@ -41,6 +41,9 @@ export const AGGREGATION_OPTIONS: { value: BIAggregation; label: string }[] = [
export const NUMERIC_AGGREGATIONS: BIAggregation[] = ['sum', 'average', 'minimum', 'maximum']
export const FILTER_OPERATOR_OPTIONS: { value: BIFilterOperator; label: string }[] = [
+ { value: 'in', label: 'Is any of' },
+ { value: 'not_in', label: 'Is none of' },
+ { value: 'between', label: 'Between' },
{ value: 'equals', label: 'Equals' },
{ value: 'not_equals', label: 'Does not equal' },
{ value: 'contains', label: 'Contains' },
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 59f95a0a35ab..e8aef12afe1b 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
@@ -5,7 +5,9 @@ import {
BIConfig,
BIEditorView,
BIField,
+ BIFilter,
DEFAULT_BI_CONFIG,
+ buildBIFilterOptionsQuery,
buildBIQuery,
createDefaultDateFilter,
defaultAggregationForField,
@@ -16,6 +18,7 @@ import {
getBISortOptions,
getBIValueSortKey,
getBIValuePillLabel,
+ getBIFilterValidationError,
isBIFieldCompatible,
isBIMeasureField,
parseBIEditorState,
@@ -62,6 +65,129 @@ const countryField: BIField = {
}
describe('BI editor query generation', () => {
+ test.each<{ filter: BIFilter; expected: string | null }>([
+ {
+ filter: { field: eventField, operator: 'in', value: '', values: ["sign'up", 'a,b', ''] },
+ expected: "event IN ('sign\\'up', 'a,b', '')",
+ },
+ {
+ filter: { field: revenueField, operator: 'not_in', value: '', values: ['0', '12.5'] },
+ expected: 'properties.revenue NOT IN (0, 12.5)',
+ },
+ {
+ filter: {
+ field: revenueField,
+ operator: 'in',
+ value: '',
+ values: ['9007199254740993', '-0.1234567890123456789', '1e3', '010', '+002.5'],
+ },
+ expected: 'properties.revenue IN (9007199254740993, -0.1234567890123456789, 1e3, 10, +2.5)',
+ },
+ {
+ filter: {
+ field: revenueField,
+ operator: 'between',
+ value: '9007199254740993',
+ valueTo: '9007199254740995',
+ },
+ expected: '(properties.revenue >= 9007199254740993 AND properties.revenue <= 9007199254740995)',
+ },
+ { filter: { field: eventField, operator: 'in', value: '', values: [] }, expected: null },
+ {
+ filter: { field: revenueField, operator: 'between', value: '0', valueTo: '20.5' },
+ expected: '(properties.revenue >= 0 AND properties.revenue <= 20.5)',
+ },
+ {
+ filter: { field: revenueField, operator: 'between', value: '', valueTo: '20' },
+ expected: '(properties.revenue <= 20)',
+ },
+ { filter: { field: revenueField, operator: 'between', value: '5' }, expected: '(properties.revenue >= 5)' },
+ { filter: { field: revenueField, operator: 'between', value: '' }, expected: null },
+ {
+ filter: {
+ field: timestampField,
+ operator: 'between',
+ value: '2026-06-01 00:00:00',
+ valueTo: '2026-06-07 23:59:59',
+ },
+ expected: "(timestamp >= '2026-06-01 00:00:00' AND timestamp <= '2026-06-07 23:59:59')",
+ },
+ {
+ filter: { field: eventField, operator: 'custom', value: '', customExpression: '1 = 0', enabled: false },
+ expected: null,
+ },
+ { filter: { field: timestampField, operator: 'last_7_days', value: '', enabled: false }, expected: null },
+ ])('builds and restores quick filter $filter.operator ($expected)', ({ filter, expected }) => {
+ const config = { ...DEFAULT_BI_CONFIG, source: eventField.source, filters: [filter] }
+ const restored = parseBIEditorState(BIEditorView.BI, JSON.stringify(config))
+ expect(restored?.config.filters).toEqual([filter])
+ const query = buildBIQuery(restored!.config)!.query
+ if (expected) {
+ expect(query).toContain(`WHERE\n ${expected}`)
+ } else {
+ expect(query).not.toContain('WHERE')
+ }
+ })
+
+ test.each(['abc', 'NaN', 'Infinity', '1e999', '0x10', '1 OR 1 = 1'])(
+ 'blocks invalid numeric filters without emitting SQL for %s',
+ (value) => {
+ for (const filter of [
+ { field: revenueField, operator: 'in', value: '', values: ['1', value] },
+ { field: revenueField, operator: 'between', value: '0', valueTo: value },
+ { field: revenueField, operator: 'equals', value },
+ ] satisfies BIFilter[]) {
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ source: eventField.source,
+ filters: [filter, { field: eventField, operator: 'in' as const, value: '' }],
+ }
+ expect(getBIFilterValidationError(filter)).toBeTruthy()
+ expect(buildBIQuery(config)).toBeNull()
+ expect(buildBIFilterOptionsQuery(config, 1)).toBeNull()
+ expect(buildBIQuery({ ...config, filters: [{ ...filter, enabled: false }] })).not.toBeNull()
+ }
+ }
+ )
+
+ it('scopes value suggestions to other enabled filters and the selected connection', () => {
+ const source = { table: 'orders', connectionId: 'example-connection' }
+ const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source,
+ filters: [
+ { field: { ...eventField, source }, operator: 'in', value: '', values: ['purchase'] },
+ { field: { ...revenueField, source }, operator: 'between', value: '10', valueTo: '100' },
+ { field: { ...timestampField, source }, operator: 'last_7_days', value: '', enabled: false },
+ ],
+ }
+ expect(buildBIFilterOptionsQuery(config, 0)).toEqual({
+ kind: NodeKind.HogQLQuery,
+ connectionId: source.connectionId,
+ query: 'SELECT DISTINCT toString(event) AS value\nFROM orders\nWHERE (event IS NOT NULL) AND ((properties.revenue >= 10 AND properties.revenue <= 100))\nLIMIT 100',
+ })
+ config.filters.push({
+ field: { ...eventField, expression: '', name: '', source },
+ operator: 'custom',
+ value: '',
+ customExpression: 'revenue > 20 OR revenue = 0',
+ })
+ expect(buildBIFilterOptionsQuery(config, 0)?.query).toContain('AND (revenue > 20 OR revenue = 0)')
+ })
+
+ test.each([{ values: [1] }, { values: 'purchase' }, { valueTo: 10 }, { enabled: 'false' }])(
+ 'rejects malformed quick filter state %j',
+ (invalid) => {
+ expect(
+ parseBIEditorState(BIEditorView.BI, {
+ ...DEFAULT_BI_CONFIG,
+ source: eventField.source,
+ filters: [{ field: eventField, operator: 'in', value: '', ...invalid }],
+ })
+ ).toBeNull()
+ }
+ )
+
it('builds a visualization node with dimensions, aggregations, and filters', () => {
const expectedQuery = [
'SELECT',
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
index 83d7304c97fe..3f9277598967 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
@@ -1,7 +1,10 @@
+import { dayjs } from 'lib/dayjs'
+
import {
DataVisualizationNode,
DatabaseSchemaTable,
DatabaseSerializedFieldType,
+ HogQLQuery,
NodeKind,
} from '~/queries/schema/schema-general'
import {
@@ -44,6 +47,9 @@ export type BIFilterOperator =
| 'equals'
| 'not_equals'
| 'contains'
+ | 'in'
+ | 'not_in'
+ | 'between'
| 'greater_than'
| 'less_than'
| 'last_7_days'
@@ -90,6 +96,22 @@ export interface BIFilter {
operator: BIFilterOperator
value: string
customExpression?: string
+ values?: string[]
+ valueTo?: string
+ enabled?: boolean
+}
+
+export function changeBIFilterOperator(filter: BIFilter, operator: BIFilterOperator): BIFilter {
+ const wasMultiple = ['in', 'not_in'].includes(filter.operator)
+ const isMultiple = ['in', 'not_in'].includes(operator)
+ if (wasMultiple === isMultiple) {
+ return { ...filter, operator }
+ }
+ return {
+ ...filter,
+ operator,
+ ...(isMultiple ? { values: filter.value ? [filter.value] : [] } : { value: filter.values?.[0] ?? '' }),
+ }
}
export interface BIConfig {
@@ -147,6 +169,9 @@ const BI_AGGREGATIONS = new Set<BIAggregation>([
'custom',
])
const BI_FILTER_OPERATORS = new Set<BIFilterOperator>([
+ 'in',
+ 'not_in',
+ 'between',
'equals',
'not_equals',
'contains',
@@ -467,6 +492,11 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
!field ||
!BI_FILTER_OPERATORS.has(filterCandidate.operator as BIFilterOperator) ||
typeof filterCandidate.value !== 'string' ||
+ (filterCandidate.values !== undefined &&
+ (!Array.isArray(filterCandidate.values) ||
+ !filterCandidate.values.every((value) => typeof value === 'string'))) ||
+ (filterCandidate.valueTo !== undefined && typeof filterCandidate.valueTo !== 'string') ||
+ (filterCandidate.enabled !== undefined && typeof filterCandidate.enabled !== 'boolean') ||
(filterCandidate.customExpression !== undefined &&
typeof filterCandidate.customExpression !== 'string')
) {
@@ -477,6 +507,9 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
operator: filterCandidate.operator as BIFilterOperator,
value: filterCandidate.value,
customExpression: filterCandidate.customExpression,
+ values: filterCandidate.values,
+ valueTo: filterCandidate.valueTo,
+ enabled: filterCandidate.enabled,
}
})
: null
@@ -616,7 +649,77 @@ function aggregationExpression(value: BIValue): string | null {
}
}
+export function getBIFilterValidationError(filter: BIFilter): string | null {
+ if (
+ filter.enabled === false ||
+ !isNumericBIField(filter.field) ||
+ ['custom', 'contains', 'is_set', 'is_not_set', 'last_7_days'].includes(filter.operator)
+ ) {
+ return null
+ }
+ const values =
+ filter.operator === 'in' || filter.operator === 'not_in'
+ ? (filter.values ?? [])
+ : [filter.value, ...(filter.operator === 'between' ? [filter.valueTo ?? ''] : [])].filter(
+ (value) => value.trim() !== ''
+ )
+ return values.some(
+ (value) =>
+ !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value.trim()) || !Number.isFinite(Number(value))
+ )
+ ? 'Enter a valid number for each filter value.'
+ : null
+}
+
+export function getBIFilterSummary(filter: BIFilter): string {
+ const dateFormat =
+ filter.field.type === 'datetime' && filter.value.slice(0, 10) === filter.valueTo?.slice(0, 10)
+ ? 'MMM D, HH:mm'
+ : filter.value.slice(0, 4) !== filter.valueTo?.slice(0, 4)
+ ? 'MMM D, YYYY'
+ : 'MMM D'
+ const formatValue = (value: string): string =>
+ isDateTimeBIField(filter.field) && dayjs(value).isValid() ? dayjs(value).format(dateFormat) : value
+ switch (filter.operator) {
+ case 'in':
+ case 'not_in': {
+ const values = filter.values ?? []
+ const selection = values.length === 1 ? values[0] || '(empty string)' : `${values.length} values`
+ return values.length ? `${filter.operator === 'not_in' ? 'Except ' : ''}${selection}` : 'All values'
+ }
+ case 'between':
+ return filter.value && filter.valueTo
+ ? `${formatValue(filter.value)} to ${formatValue(filter.valueTo)}`
+ : filter.value
+ ? `From ${formatValue(filter.value)}`
+ : filter.valueTo
+ ? `Up to ${formatValue(filter.valueTo)}`
+ : 'All values'
+ case 'is_set':
+ return 'Has a value'
+ case 'is_not_set':
+ return 'Has no value'
+ case 'last_7_days':
+ return 'Last 7 days'
+ case 'custom':
+ return filter.customExpression?.trim() || 'Add SQL condition'
+ default: {
+ const prefix = {
+ equals: '',
+ not_equals: 'Not ',
+ contains: 'Contains ',
+ greater_than: '> ',
+ less_than: '< ',
+ }[filter.operator]
+ return filter.value ? `${prefix}${filter.value}` : 'All values'
+ }
+ }
+}
+
function filterExpression(filter: BIFilter): string | null {
+ if (filter.enabled === false) {
+ return null
+ }
const field = fieldExpression(filter.field)
if (filter.operator === 'custom') {
@@ -632,14 +735,27 @@ function filterExpression(filter: BIFilter): string | null {
if (filter.operator === 'last_7_days') {
return `${field} >= now() - INTERVAL 7 DAY`
}
+ // Strip leading zeroes so decimal input cannot become an octal HogQL literal.
+ const literal = (value: string): string =>
+ isNumericBIField(filter.field) ? value.trim().replace(/^([+-]?)0+(?=\d)/, '$1') : escapeHogQLString(value)
+ if (filter.operator === 'in' || filter.operator === 'not_in') {
+ const values = filter.values ?? []
+ return values.length
+ ? `${field} ${filter.operator === 'in' ? 'IN' : 'NOT IN'} (${values.map(literal).join(', ')})`
+ : null
+ }
+ if (filter.operator === 'between') {
+ const bounds = [
+ filter.value.trim() ? `${field} >= ${literal(filter.value)}` : null,
+ filter.valueTo?.trim() ? `${field} <= ${literal(filter.valueTo)}` : null,
+ ].filter(Boolean)
+ return bounds.length ? `(${bounds.join(' AND ')})` : null
+ }
if (!filter.value.trim()) {
return null
}
- const value =
- isNumericBIField(filter.field) && Number.isFinite(Number(filter.value))
- ? String(Number(filter.value))
- : escapeHogQLString(filter.value)
+ const value = literal(filter.value)
switch (filter.operator) {
case 'equals':
@@ -655,6 +771,31 @@ function filterExpression(filter: BIFilter): string | null {
}
}
+export function buildBIFilterOptionsQuery(config: BIConfig, index: number): HogQLQuery | null {
+ const filter = config.filters[index]
+ if (
+ !config.source ||
+ !filter?.field.expression.trim() ||
+ config.filters.some((other, otherIndex) => otherIndex !== index && getBIFilterValidationError(other))
+ ) {
+ return null
+ }
+ const expression = fieldExpression(filter.field)
+ const conditions = config.filters
+ .filter(
+ (other, otherIndex) =>
+ otherIndex !== index &&
+ (other.field.expression.trim() || other.field.name.trim() || other.operator === 'custom')
+ )
+ .map(filterExpression)
+ .filter((condition): condition is string => !!condition)
+ return {
+ kind: NodeKind.HogQLQuery,
+ connectionId: config.source.connectionId,
+ query: `SELECT DISTINCT toString(${expression}) AS value\nFROM ${escapePropertyAsHogQLIdentifier(config.source.table)}\nWHERE ${[`${expression} IS NOT NULL`, ...conditions].map((condition) => `(${condition})`).join(' AND ')}\nLIMIT 100`,
+ }
+}
+
interface BIConfiguredValue {
value: BIValue
expression: string
@@ -843,7 +984,7 @@ function buildOrderByExpression(
}
export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
- if (!config.source) {
+ if (!config.source || config.filters.some(getBIFilterValidationError)) {
return null
}
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterEditor.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterEditor.tsx
index 17dbefd1bbbd..5e77147e7320 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterEditor.tsx
@@ -1,15 +1,15 @@
import { useActions, useValues } from 'kea'
import { IconPencil } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
+import { LemonButton, LemonCheckbox, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
import { HogQLDropdown } from 'lib/components/HogQLDropdown/HogQLDropdown'
-import { dayjs } from 'lib/dayjs'
-import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
+
+import { BIFilterValueInput } from 'products/data_warehouse/frontend/bi/BIFilterValueInput'
import { biEditorLogic } from '../biEditorLogic'
import { DATE_BUCKET_OPTIONS, FILTER_OPERATOR_OPTIONS } from '../biEditorOptions'
-import { isDateTimeBIField } from '../biEditorTypes'
+import { isDateTimeBIField, isNumericBIField } from '../biEditorTypes'
export function BIFilterEditor({ index, onDone }: { index: number; onDone: () => void }): JSX.Element | null {
const { config } = useValues(biEditorLogic)
@@ -19,7 +19,7 @@ export function BIFilterEditor({ index, onDone }: { index: number; onDone: () =>
setFieldExpression,
setFilterCustomExpression,
setFilterOperator,
- setFilterValue,
+ updateFilter,
} = useActions(biEditorLogic)
const filter = config.filters[index]
if (!filter) {
@@ -28,8 +28,6 @@ export function BIFilterEditor({ index, onDone }: { index: number; onDone: () =>
const { field } = filter
const needsValue = !['last_7_days', 'is_set', 'is_not_set', 'custom'].includes(filter.operator)
- const includesTime = field.type === 'datetime'
- const selectedDate = filter.value && dayjs(filter.value).isValid() ? dayjs(filter.value) : null
return (
<div className="flex w-80 flex-col gap-3 p-1">
@@ -64,15 +62,16 @@ export function BIFilterEditor({ index, onDone }: { index: number; onDone: () =>
<LemonLabel>Condition</LemonLabel>
<LemonSelect
value={filter.operator}
- options={FILTER_OPERATOR_OPTIONS.map((option) => ({
- ...option,
- disabledReason:
- option.value === 'last_7_days' && !isDateTimeBIField(field)
- ? 'Choose a date or date-time field'
- : undefined,
- }))}
+ options={FILTER_OPERATOR_OPTIONS.filter(
+ (option) =>
+ option.value === filter.operator ||
+ ((option.value !== 'last_7_days' || isDateTimeBIField(field)) &&
+ (option.value !== 'between' || isDateTimeBIField(field) || isNumericBIField(field)))
+ )}
onChange={(operator) => setFilterOperator(index, operator)}
size="small"
+ aria-label={`${field.name} filter condition`}
+ data-attr="bi-filter-condition"
/>
</div>
{filter.operator === 'custom' ? (
@@ -98,35 +97,15 @@ export function BIFilterEditor({ index, onDone }: { index: number; onDone: () =>
) : needsValue ? (
<div className="flex flex-col gap-1">
<LemonLabel>Value</LemonLabel>
- {isDateTimeBIField(field) ? (
- <LemonCalendarSelectInput
- value={selectedDate}
- onChange={(date) =>
- setFilterValue(
- index,
- date?.format(includesTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD') ?? ''
- )
- }
- granularity={includesTime ? 'minute' : 'day'}
- format={includesTime ? 'MMM D, YYYY HH:mm' : 'MMM D, YYYY'}
- use24HourFormat
- clearable
- placeholder={includesTime ? 'Select date and time' : 'Select date'}
- buttonProps={{ size: 'small', 'aria-label': `${field.name} filter date` }}
- />
- ) : (
- <LemonInput
- value={filter.value}
- onChange={(value) => setFilterValue(index, value)}
- onPressEnter={onDone}
- placeholder="Value"
- aria-label={`${field.name} filter value`}
- size="small"
- autoFocus
- />
- )}
+ <BIFilterValueInput index={index} />
</div>
) : null}
+ <LemonCheckbox
+ checked={filter.enabled !== false}
+ onChange={(enabled) => updateFilter(index, { enabled })}
+ label="Apply filter"
+ size="small"
+ />
<div className="flex justify-between gap-2">
<LemonButton
type="tertiary"
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterPill.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterPill.tsx
index 6853c813defd..329fb3cae13d 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterPill.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFilterPill.tsx
@@ -2,23 +2,18 @@ import { useActions, useValues } from 'kea'
import { LemonDropdown } from '@posthog/lemon-ui'
+import { cn } from 'lib/utils/css-classes'
+
import { biEditorLogic } from '../biEditorLogic'
-import { FILTER_OPERATOR_OPTIONS } from '../biEditorOptions'
-import { BIFilter, getBIFieldPillLabel, getBIShelfEditorKey } from '../biEditorTypes'
+import {
+ getBIFieldPillLabel,
+ getBIFilterSummary,
+ getBIFilterValidationError,
+ getBIShelfEditorKey,
+} from '../biEditorTypes'
import { BIFilterEditor } from './BIFilterEditor'
import { BIPill } from './BIPill'
-function filterSummary(filter: BIFilter): string | undefined {
- const operatorLabel = FILTER_OPERATOR_OPTIONS.find((option) => option.value === filter.operator)?.label
- if (filter.operator === 'custom') {
- return filter.customExpression?.trim() || undefined
- }
- if (['last_7_days', 'is_set', 'is_not_set'].includes(filter.operator)) {
- return operatorLabel?.toLowerCase()
- }
- return filter.value.trim() ? `${operatorLabel?.toLowerCase()} ${filter.value}` : undefined
-}
-
export function BIFilterPill({ index }: { index: number }): JSX.Element | null {
const { config, activeExpressionEditorId } = useValues(biEditorLogic)
const { setActiveExpressionEditorId } = useActions(biEditorLogic)
@@ -35,7 +30,6 @@ export function BIFilterPill({ index }: { index: number }): JSX.Element | null {
}
}
const label = getBIFieldPillLabel(filter.field)
- const summary = filterSummary(filter)
return (
<LemonDropdown
@@ -48,11 +42,15 @@ export function BIFilterPill({ index }: { index: number }): JSX.Element | null {
<BIPill
kind="filter"
label={label}
- detail={summary}
+ detail={getBIFilterValidationError(filter) ? 'Invalid' : filter.enabled === false ? 'Off' : undefined}
+ title={`${label}: ${getBIFilterSummary(filter)}`}
shelf="filters"
index={index}
incomplete={!filter.field.expression.trim() && !filter.customExpression?.trim()}
- className="w-full justify-between"
+ className={cn(
+ 'h-5 w-full justify-between px-1.5 font-normal',
+ filter.enabled === false && 'opacity-50'
+ )}
aria-label={`${label} filter`}
data-attr="bi-editor-filters-pill"
/>
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFiltersCard.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFiltersCard.tsx
index bbc57ee9b978..e3aa70a17691 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIFiltersCard.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIFiltersCard.tsx
@@ -14,7 +14,7 @@ export function BIFiltersCard(): JSX.Element {
return (
<BIShelfCard title="Filters">
- <BIShelfDropTarget shelf="filters" className="flex min-h-12 flex-col gap-1 border border-dashed p-1">
+ <BIShelfDropTarget shelf="filters" className="flex min-h-6 flex-col gap-0.5">
{config.filters.length > 0 ? (
config.filters.map((filter, index) => <BIFilterPill key={filter.field.id} index={index} />)
) : (
@@ -29,7 +29,7 @@ export function BIFiltersCard(): JSX.Element {
onClick={() => addBlankFieldToShelf('filters')}
data-attr="bi-editor-filters-add-field"
>
- Add a calculated filter
+ Add filter
</LemonButton>
</BIShelfCard>
)
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIMarksCard.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIMarksCard.tsx
index dcd541a77caf..0f17d3a3026b 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIMarksCard.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIMarksCard.tsx
@@ -23,14 +23,12 @@ export function BIMarksCard(): JSX.Element {
icon: option.icon,
}))}
onChange={setChartType}
- size="small"
+ size="xsmall"
fullWidth
aria-label="Mark type"
data-attr="bi-editor-mark-type"
+ tooltip="Change how measures on Rows are displayed"
/>
- <span className="text-xs text-secondary">
- Measures on rows set the values. Change how a measure is calculated from its menu.
- </span>
</BIShelfCard>
)
}
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfCard.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfCard.tsx
index afa5cc5b5796..5b8a31e07d9d 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfCard.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShelfCard.tsx
@@ -3,8 +3,8 @@ import type { ReactNode } from 'react'
/** A titled card in the column next to the data pane, like the Filters and Marks cards. */
export function BIShelfCard({ title, children }: { title: string; children: ReactNode }): JSX.Element {
return (
- <section className="flex flex-col gap-1.5 border-b p-2">
- <h3 className="m-0 text-sm font-semibold">{title}</h3>
+ <section className="flex flex-col gap-1 border-b px-2 py-1.5">
+ <h3 className="m-0 text-xs font-semibold">{title}</h3>
{children}
</section>
)
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShowMe.tsx b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShowMe.tsx
index 3c58025d83dc..fa22d598a3f5 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/components/BIShowMe.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/components/BIShowMe.tsx
@@ -24,7 +24,7 @@ export function BIShowMe({ docked }: { docked: boolean }): JSX.Element {
const describedFit = describedOption ? chartFits[describedOption.value] : undefined
return (
- <div className="flex w-44 flex-col">
+ <div className={cn('flex flex-col', docked ? 'w-full' : 'w-44')}>
<div className="flex min-h-7 items-center justify-between px-2 pt-2">
<span className="text-sm font-semibold">Show me</span>
{docked ? (
@@ -38,7 +38,7 @@ export function BIShowMe({ docked }: { docked: boolean }): JSX.Element {
/>
) : null}
</div>
- <div className="grid grid-cols-3 gap-1 p-2" role="group" aria-label="Chart type">
+ <div className="grid grid-cols-3 gap-1 p-2 @6xl/bi-editor:grid-cols-6" role="group" aria-label="Chart type">
{options.map((option) => {
const fits = chartFits[option.value]?.fits ?? true
const selected = config.chartType === option.value
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index e7d7bb091ac7..133d049a764c 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -2749,7 +2749,7 @@ describe('sqlEditorLogic', () => {
}
)
- test.each(['disable', 'sql', 'clear', 'unchanged'] as const)(
+ test.each(['disable', 'sql', 'clear', 'invalid', 'unchanged'] as const)(
'handles a pending automatic query when the worksheet is %s',
async (transition) => {
logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
@@ -2769,6 +2769,22 @@ describe('sqlEditorLogic', () => {
logic.actions.setQueryInput('SELECT 42')
} else if (transition === 'clear') {
biLogic.actions.resetConfig()
+ } else if (transition === 'invalid') {
+ biLogic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: {
+ ...config,
+ filters: [
+ {
+ field: { ...eventField, type: 'integer' },
+ operator: 'between',
+ value: '0',
+ valueTo: 'abc',
+ },
+ ],
+ },
+ })
+ biLogic.actions.setLimit(10000)
}
await jest.advanceTimersByTimeAsync(500)
expect(runQuery).toHaveBeenCalledTimes(transition === 'unchanged' ? 1 : 0)
@@ -2851,6 +2867,42 @@ describe('sqlEditorLogic', () => {
filters: [{ ...persistedConfig.filters[0], value: 'purchase' }],
})
+ await expectLogic(biLogic, () => biLogic.actions.setFilterOperator(0, 'in')).toFinishAllListeners()
+ expect(biLogic.values.config.filters[0].values).toEqual(['purchase'])
+ await expectLogic(biLogic, () =>
+ biLogic.actions.updateFilter(0, { values: ['purchase', 'renewal'] })
+ ).toFinishAllListeners()
+ expect(logic.values.queryInput).toContain("event IN ('purchase', 'renewal')")
+ await expectLogic(biLogic, () => biLogic.actions.updateFilter(0, { enabled: false })).toFinishAllListeners()
+ expect(logic.values.queryInput).not.toContain('WHERE')
+ expect(router.values.hashParams.bi.filters[0]).toEqual(
+ expect.objectContaining({ enabled: false, values: ['purchase', 'renewal'] })
+ )
+ await expectLogic(biLogic, () => biLogic.actions.updateFilter(0, { enabled: true })).toFinishAllListeners()
+ expect(logic.values.queryInput).toContain("event IN ('purchase', 'renewal')")
+ await expectLogic(biLogic, () => biLogic.actions.updateFilter(0, { values: [] })).toFinishAllListeners()
+ expect(logic.values.queryInput).not.toContain('WHERE')
+ await expectLogic(biLogic, () => biLogic.actions.setFilterOperator(0, 'equals')).toFinishAllListeners()
+ expect(biLogic.values.config.filters[0].value).toBe('')
+
+ biLogic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: {
+ ...config,
+ filters: [{ field: { ...eventField, type: 'integer' }, operator: 'between', value: '0' }],
+ },
+ })
+ await expectLogic(biLogic, () => biLogic.actions.updateFilter(0, { valueTo: 'abc' })).toFinishAllListeners()
+ const lastRunQuery = logic.values.lastRunQuery
+ await expectLogic(logic, () => logic.actions.runQuery()).toFinishAllListeners()
+ expect(logic.values.error).toBe('Fix invalid worksheet filters before running the query.')
+ expect(logic.values.lastRunQuery).toEqual(lastRunQuery)
+ await expectLogic(biLogic, () =>
+ biLogic.actions.updateFilter(0, { valueTo: '9007199254740993' })
+ ).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.runQuery()).toFinishAllListeners()
+ expect(logic.values.lastRunQuery?.source.query).toContain('event <= 9007199254740993')
+
biLogic.unmount()
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 298c31cb6a0a..4716497ad7bf 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -119,7 +119,13 @@ import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogi
import type { DataWarehouseSavedQuerySummary } from '../saved_queries/dataWarehouseViewsLogic'
import { validateSavedQueryName } from '../saved_queries/savedQueryNameValidation'
import { captureBIEditorQueryRun, captureBIEditorQuerySaved } from './bi/biEditorAnalytics'
-import { BIEditorState, BIEditorView, buildBIQuery, parseBIEditorState } from './bi/biEditorTypes'
+import {
+ BIEditorState,
+ BIEditorView,
+ buildBIQuery,
+ getBIFilterValidationError,
+ parseBIEditorState,
+} from './bi/biEditorTypes'
import { connectionSelectorLogic } from './connectionSelectorLogic'
import { draftsLogic } from './draftsLogic'
import { fixSQLErrorsLogic } from './fixSQLErrorsLogic'
@@ -2256,6 +2262,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
},
runQuery: ({ queryOverride, switchTab }) => {
const biEditorState = getActiveBIEditorState()
+ if (
+ !queryOverride &&
+ biEditorState?.editorView === BIEditorView.BI &&
+ biEditorState.config.filters.some(getBIFilterValidationError)
+ ) {
+ actions.setError('Fix invalid worksheet filters before running the query.')
+ return
+ }
captureBIEditorQueryRun(biEditorState)
const biQuery =
!queryOverride && biEditorState?.editorView === BIEditorView.BI
diff --git a/products/data_warehouse/frontend/bi/BIFilterControl.tsx b/products/data_warehouse/frontend/bi/BIFilterControl.tsx
new file mode 100644
index 000000000000..2ef96509f272
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/BIFilterControl.tsx
@@ -0,0 +1,82 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronDown } from '@posthog/icons'
+import { LemonButton, LemonCheckbox, LemonDropdown } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { biEditorLogic } from 'scenes/data-warehouse/editor/bi/biEditorLogic'
+import {
+ getBIFieldPillLabel,
+ getBIFilterSummary,
+ getBIFilterValidationError,
+ getBIShelfEditorKey,
+} from 'scenes/data-warehouse/editor/bi/biEditorTypes'
+import { BIFilterEditor } from 'scenes/data-warehouse/editor/bi/components/BIFilterEditor'
+
+export function BIFilterControl({ index }: { index: number }): JSX.Element | null {
+ const { config, activeExpressionEditorId } = useValues(biEditorLogic)
+ const { updateFilter, setActiveExpressionEditorId } = useActions(biEditorLogic)
+ const filter = config.filters[index]
+ if (!filter) {
+ return null
+ }
+ const label = getBIFieldPillLabel(filter.field)
+ const editorKey = `${getBIShelfEditorKey('filters', filter.field.id)}:quick`
+ const validationError = getBIFilterValidationError(filter)
+ const summary = getBIFilterSummary(filter)
+ const close = (): void => {
+ if (activeExpressionEditorId === editorKey) {
+ setActiveExpressionEditorId(null)
+ }
+ }
+
+ return (
+ <div className="flex min-w-0 flex-col gap-0.5" data-attr="bi-filter-control">
+ <LemonCheckbox
+ checked={filter.enabled !== false}
+ onChange={(enabled) => updateFilter(index, { enabled })}
+ label={
+ <span
+ className={cn(
+ 'block truncate text-xs font-normal',
+ filter.enabled === false && 'text-tertiary'
+ )}
+ >
+ {label}
+ </span>
+ }
+ aria-label={`Apply ${label} filter`}
+ size="xsmall"
+ className="min-w-0 [&_.LemonCheckbox__label]:min-w-0"
+ labelClassName="min-w-0 flex-1 !min-h-4 !leading-4"
+ data-attr="bi-filter-enabled"
+ />
+ <LemonDropdown
+ visible={activeExpressionEditorId === editorKey}
+ onVisibilityChange={(visible) => (visible ? setActiveExpressionEditorId(editorKey) : close())}
+ closeOnClickInside={false}
+ placement="left-start"
+ overlay={<BIFilterEditor index={index} onDone={close} />}
+ >
+ <LemonButton
+ type="secondary"
+ size="xxsmall"
+ fullWidth
+ sideIcon={<IconChevronDown />}
+ status={validationError ? 'danger' : 'default'}
+ className={cn('font-normal', filter.enabled === false && 'opacity-50')}
+ tooltip={
+ validationError ||
+ (filter.operator === 'between'
+ ? `${filter.value || 'Any'} to ${filter.valueTo || 'any'}`
+ : summary)
+ }
+ aria-label={`Edit ${label} filter values`}
+ data-attr="bi-filter-edit-values"
+ >
+ <span className="truncate font-normal">{validationError ? 'Invalid number' : summary}</span>
+ </LemonButton>
+ </LemonDropdown>
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/bi/BIFilterValueInput.tsx b/products/data_warehouse/frontend/bi/BIFilterValueInput.tsx
new file mode 100644
index 000000000000..8ec62ba789e3
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/BIFilterValueInput.tsx
@@ -0,0 +1,128 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { LemonButton, LemonInput, LemonInputSelect } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
+import { biEditorLogic } from 'scenes/data-warehouse/editor/bi/biEditorLogic'
+import {
+ buildBIFilterOptionsQuery,
+ getBIFilterValidationError,
+ isDateTimeBIField,
+} from 'scenes/data-warehouse/editor/bi/biEditorTypes'
+
+import { biFilterValuesLogic } from './biFilterValuesLogic'
+
+export function BIFilterValueInput({ index }: { index: number }): JSX.Element | null {
+ const { config } = useValues(biEditorLogic)
+ const { setFilterValue, updateFilter } = useActions(biEditorLogic)
+ const filter = config.filters[index]
+ const [focused, setFocused] = useState(false)
+ const valuesLogic = biFilterValuesLogic({ query: buildBIFilterOptionsQuery(config, index), active: focused })
+ const { options, optionsLoading, optionsError } = useValues(valuesLogic)
+ const { loadOptions } = useActions(valuesLogic)
+ if (!filter || ['last_7_days', 'is_set', 'is_not_set', 'custom'].includes(filter.operator)) {
+ return null
+ }
+ const validationError = getBIFilterValidationError(filter)
+ if (filter.operator === 'in' || filter.operator === 'not_in') {
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ <LemonInputSelect
+ mode="multiple"
+ value={filter.values ?? []}
+ options={(options ?? []).map((value) => ({ key: value, label: value || '(empty string)' }))}
+ loading={optionsLoading}
+ status={validationError ? 'danger' : 'default'}
+ onFocus={() => setFocused(true)}
+ onBlur={() => setFocused(false)}
+ onChange={(values) => updateFilter(index, { values })}
+ placeholder={filter.operator === 'in' ? 'All values' : 'No excluded values'}
+ title={`Values for ${filter.field.name}`}
+ allowCustomValues
+ disableCommaSplitting
+ bulkActions="clear-all"
+ size="small"
+ className="[&_input]:min-w-20"
+ data-attr="bi-filter-values"
+ fullWidth
+ />
+ {validationError && (
+ <span role="alert" className="text-xs text-danger">
+ {validationError}
+ </span>
+ )}
+ {optionsError ? (
+ <div className="text-xs text-danger">
+ <span>Could not load suggestions. You can still enter values.</span>
+ <LemonButton size="xsmall" onClick={() => loadOptions()} loading={optionsLoading}>
+ Retry
+ </LemonButton>
+ </div>
+ ) : options?.length === 100 ? (
+ <span className="text-xs text-tertiary">Showing 100 suggestions. Type to add another value.</span>
+ ) : null}
+ </div>
+ )
+ }
+ const isRange = filter.operator === 'between'
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ {(isRange ? (['from', 'to'] as const) : (['from'] as const)).map((bound) => {
+ const value = bound === 'from' ? filter.value : (filter.valueTo ?? '')
+ const onChange = (next: string): void => {
+ if (bound === 'from') {
+ setFilterValue(index, next)
+ } else {
+ updateFilter(index, { valueTo: next })
+ }
+ }
+ const label = `${filter.field.name} filter ${isRange ? bound : 'value'}`
+ return (
+ <div key={bound} className="flex min-w-0 flex-col gap-1">
+ {isRange ? (
+ <span className="text-xs text-secondary">
+ {bound === 'from' ? 'From (inclusive)' : 'To (inclusive)'}
+ </span>
+ ) : null}
+ {isDateTimeBIField(filter.field) ? (
+ <LemonCalendarSelectInput
+ value={value && dayjs(value).isValid() ? dayjs(value) : null}
+ onChange={(date) =>
+ onChange(
+ date?.format(
+ filter.field.type === 'datetime' ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'
+ ) ?? ''
+ )
+ }
+ granularity={filter.field.type === 'datetime' ? 'minute' : 'day'}
+ format={filter.field.type === 'datetime' ? 'MMM D, YYYY HH:mm' : 'MMM D, YYYY'}
+ use24HourFormat
+ clearable
+ placeholder={
+ isRange ? (bound === 'from' ? 'No lower bound' : 'No upper bound') : 'Select date'
+ }
+ buttonProps={{ size: 'small', 'aria-label': label, fullWidth: true }}
+ />
+ ) : (
+ <LemonInput
+ value={value}
+ onChange={onChange}
+ placeholder={isRange ? (bound === 'from' ? 'No minimum' : 'No maximum') : 'Value'}
+ aria-label={label}
+ size="small"
+ status={validationError ? 'danger' : 'default'}
+ />
+ )}
+ </div>
+ )
+ })}
+ {validationError && (
+ <span role="alert" className="text-xs text-danger">
+ {validationError}
+ </span>
+ )}
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/bi/biFilterValuesLogic.test.ts b/products/data_warehouse/frontend/bi/biFilterValuesLogic.test.ts
new file mode 100644
index 000000000000..2406f3d9f438
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/biFilterValuesLogic.test.ts
@@ -0,0 +1,34 @@
+import { expectLogic } from 'kea-test-utils'
+
+import * as queryRunner from '~/queries/query'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { biFilterValuesLogic } from './biFilterValuesLogic'
+
+describe('BI filter suggestions', () => {
+ beforeEach(() => initKeaTests())
+
+ it('loads a changed query while the input remains focused', async () => {
+ const query = { kind: NodeKind.HogQLQuery as const, query: 'SELECT DISTINCT event FROM events LIMIT 100' }
+ const performQuery = jest
+ .spyOn(queryRunner, 'performQuery')
+ .mockResolvedValue({ results: [['first']] } as never)
+ const initial = biFilterValuesLogic({ query, active: false })
+ initial.mount()
+ expect(performQuery).not.toHaveBeenCalled()
+ await expectLogic(initial, () => {
+ biFilterValuesLogic({ query, active: true })
+ }).toFinishAllListeners()
+ expect(initial.values.options).toEqual(['first'])
+ initial.unmount()
+
+ performQuery.mockResolvedValue({ results: [['second']] } as never)
+ const changed = biFilterValuesLogic({ query: { ...query, query: `${query.query} OFFSET 1` }, active: true })
+ changed.mount()
+ await expectLogic(changed).toDispatchActions(['loadOptionsSuccess'])
+ expect(changed.values.options).toEqual(['second'])
+ changed.unmount()
+ performQuery.mockRestore()
+ })
+})
diff --git a/products/data_warehouse/frontend/bi/biFilterValuesLogic.ts b/products/data_warehouse/frontend/bi/biFilterValuesLogic.ts
new file mode 100644
index 000000000000..3cceca1f3024
--- /dev/null
+++ b/products/data_warehouse/frontend/bi/biFilterValuesLogic.ts
@@ -0,0 +1,89 @@
+import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { performQuery } from '~/queries/query'
+import { HogQLQuery } from '~/queries/schema/schema-general'
+
+export interface BIFilterValuesLogicProps {
+ query: HogQLQuery | null
+ active?: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biFilterValuesLogicValues {
+ options: string[] | null
+ optionsError: string | null
+ optionsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biFilterValuesLogicActions {
+ loadOptions: (_: void) => void
+ loadOptionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOptionsSuccess: (
+ options: string[],
+ payload?: void
+ ) => {
+ options: string[]
+ payload?: void
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biFilterValuesLogicMeta {
+ key: string
+}
+
+export type biFilterValuesLogicType = MakeLogicType<
+ biFilterValuesLogicValues,
+ biFilterValuesLogicActions,
+ BIFilterValuesLogicProps,
+ biFilterValuesLogicMeta
+>
+
+export const biFilterValuesLogic = kea<biFilterValuesLogicType>([
+ props({} as BIFilterValuesLogicProps),
+ key((props) => JSON.stringify(props.query)),
+ path((key) => ['products', 'data_warehouse', 'frontend', 'bi', 'biFilterValuesLogic', key]),
+ loaders(({ props }) => ({
+ options: [
+ null as string[] | null,
+ {
+ loadOptions: async (_: void, breakpoint): Promise<string[]> => {
+ if (!props.query) {
+ return []
+ }
+ const response = await performQuery(props.query)
+ breakpoint()
+ return response.results.map((row) => String(row[0])).sort()
+ },
+ },
+ ],
+ })),
+ reducers({
+ optionsError: [
+ null as string | null,
+ {
+ loadOptions: () => null,
+ loadOptionsSuccess: () => null,
+ loadOptionsFailure: (_, { error }) => error,
+ },
+ ],
+ }),
+ afterMount(({ actions, props }) => {
+ if (props.active) {
+ actions.loadOptions()
+ }
+ }),
+ propsChanged(({ actions, values, props }) => {
+ if (props.active && values.options === null && !values.optionsLoading && !values.optionsError) {
+ actions.loadOptions()
+ }
+ }),
+])