: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): apply dashboard filters and add date controls (#112122)
Marius Andra1b4e869e914b
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex c08bc54db9e2..2d6e21b35404 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -26,6 +26,8 @@ Saving a worksheet as an insight preserves its connection, table, shelves, measuOlder saves containing only SQL still open in the SQL editor. Their original shelves cannot be reconstructed without the worksheet configuration from a draft or shared URL.+The worksheet date picker supports rolling windows, fixed ranges, this/last month and quarter, and year to date. **Date** selects the column that receives dashboard date ranges; **No date column** explicitly opts out. A dashboard range replaces the worksheet range. Dashboard property filters combine with worksheet conditions. Event-based tables retain standard PostHog property filtering with any date-column selection, using `{filters.native(date_expression)}` or `{filters.native(null)}` when overriding the default date column. Other tables bind dashboard property keys to worksheet fields, including the property key in a field such as `properties.plan`. Unmapped or ambiguous property keys produce a query error instead of silently applying the wrong filter. Reopen and save older BI worksheets to update their generated SQL with dashboard-aware placeholders.+Use the table picker in the data pane to browse PostHog, warehouse, view, and system tables, with direct-connection tables grouped by schema.The selected table is highlighted; expanding a folder does not select it.Direct connections group tables by schema. Search matches table and folder names without changing the sidebar search.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 04c67c757f1a..df0044f56b58 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9547,41 +9547,41 @@ snapshots:scenes-app-data-warehouse-settings-schemas--multi-schema--light:hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--dark:- hash: v1.k794b7964.3330f18f8671269ed326a3e6d33e4a91d6815a510c494623079113d4053c2dcd.4NfZi4xA0rbSHgQPo54O-aoO2onljKMXxvgIpu3rl_c+ hash: v1.k794b7964.d974890788e1b5c6e0612f1414c1fddf0bd17b5cd1946e059b75e5c67626b265.ZdKUpc_7P063x9hsZsEv5oyBQ0pTWlQkbyj3NxHajn4scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:- hash: v1.k794b7964.647495fd0c0f29fb3d59674e1e9f84b6c358f90a46bead4277253f6f58936c67.th8gTrD9KuSj5QxxTfX4Ec6p2hT9fHjl7dFm84Dz6oc+ hash: v1.k794b7964.59b4431c1c66fbeccdb380fbe3061b503b165b885858360e4c717cf2aed9f45d._6s9YXfYDH3I0OYh0On74OprQckRDkXCnbGJk6dVaacscenes-app-data-warehouse-sql-editor--bi-connections--dark:- hash: v1.k794b7964.1848c8f6b80d3b2b49bba8d0901129024d39906ab7258952cf0eb5c416b17c66.R38EzFwqrPPZMuedamgLCH3O0Oc5fKR_iMObVap7vts+ hash: v1.k794b7964.21db0db416dae779e29a200bf20098835b6697820e9c8c8f83a83431fd6aa6c3.eOVi8lx-ptmIAwLjW2luhAXdHaDTXKE-BRgqiRCwRoEscenes-app-data-warehouse-sql-editor--bi-connections--light:- hash: v1.k794b7964.ae3fc19c0b796602c9d1a016253b5919e377f3e301611a0e157d2a7ddc10dba5.MjU1aC2l6159CEzChARl9FJLK4ARqrtkS-ik0ZM2W0I+ hash: v1.k794b7964.f783145262bef5849937151f085f59cda0f60ebb20fd0fa601d318b529e1d6c6.Hj-7-UypjU2RfkegVlJFUUpRLQUKOp415WXJKsIFDaIscenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:- hash: v1.k794b7964.ae1de341b55322136ee1d80c62c0dedd6932fea9e589c24727a46307aaef35d0.AMXHYOo9nNMMIYojTy8mQN_bq1fAXOYEuzM4EjsoO3A+ hash: v1.k794b7964.bc68d1229339cd021301f8ef8275693a0e2c045dcb3ac740bcfb27eb26cb9459.M7j-horfW3uRUW53GS2dGKkHMQGgTegra-XAedoP2jMscenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:- hash: v1.k794b7964.573b004f45ca8ad619f703f18396c34dd045982314693e07806aa5c64f447562.GfKnUQ1qwUTm3SwtUhhKgZeZS8kiOuYEsMfCu9zFNcs+ hash: v1.k794b7964.6cd25146afa877d1c17afdc2cc39295b04877fec5c051fab1364717a2591b05a.iDScPI6Bq4P-WW4g3GKaW1GTOFpWn4gSWO37rpr_nSkscenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:- hash: v1.k794b7964.04285a5a664fe7a62a1739dd6cb60a683cc50462c210d1a877c815ba5493eeea.uoztjbj7h-Qeh1H-mCvY8nDpWxrzJ7yN5tG3mWov5WI+ hash: v1.k794b7964.c595896d97450a63a8cfda5d6024a4f117a781e675908f371a995be4f040210d.8QX_6pcXJ2Tg65hLue1pj8EH0UcwHB1J_O6BBpUtBoQscenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:- hash: v1.k794b7964.db347fb25d97dfe002e42c9055fb679b3747392084e6ab38a13485524d010d33.ufzsoUIKgqJ5r3F5P-xtyxRth-aVYT-BzjqHYeovLqo+ hash: v1.k794b7964.e72c20769ccdee6ab14529fef33535278c318366ce821f0832189fb6c5d12cc6.k7AA7bl7-ccEd4ffRYLfJvNSlhHUo5IVNjLi2ENsmz0scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:hash: v1.k794b7964.e96e5bd64e5c355152d4f91ae58100f74aaf16f50c4dc6b65fe01282ce454dad.xY9LiVJ2cUp5i0jqV7OvXGOf83E2dw0qTS9d3CzgOiYscenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:hash: v1.k794b7964.81e44e31cf9a3a66cf699ee4aaa6d15ff981d48e2f4d63289275f83689a61102.3Sb3cTvLqoLdO5Basj36wcg6jbUjGyVWuLTq1J5zc8kscenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:- hash: v1.k794b7964.ea0e6791b3e86157fe44a8fa51f23ed0525082d7ecc7f7127d24acb4e57f2fc9.YsWnPfpWFGAfnxNSxOrQIqoND_o6_A312tXKebPWESc+ hash: v1.k794b7964.7aa3ce1ca0ddbf4cc88ca87fe9f538a2e309a0eac8ce40317b696a503e5c9886.gY_yAskTW8CBQWsR6bvyOBzxPdTTiyd79RHV3WMyLdkscenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:- hash: v1.k794b7964.f317dae7801c8cd9cccd242f4c503c1a214fc8ab1a1256a4463ff6f5af6efb74.Cldw2qKSibPuUxoM_9a6VQzN9_vK23gCnlQjBHPC23Y+ hash: v1.k794b7964.7bc4acb07b01c453c74b160c6a90548ec9b6d708c559c5d70843875de5722df9.uiBpmyXUGsXgUWZS2r1V-dKddo5DAUe51vAGNEbxxo8scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:- hash: v1.k794b7964.da3bfb1b7f99f3b57a450e797e903f3276e2af2b6199b877aed4e05616e9c8cf.Fl7XNBtizg7jFS__JuQaReAdiJLki6c-8TyhtatElng+ hash: v1.k794b7964.833eae8ac76fa742aecd5194c3b81df2f47d922b010ac3b01dc2eb03715c6e33.qJSwQsYj-E5tK1oqe2-qLTHN3lJ6gfsnLvq73-MBTWcscenes-app-data-warehouse-sql-editor--bi-quick-filters--light:- hash: v1.k794b7964.90288543ca678488bc533702ca2d6431c4b78a0830c32fdbd188032df3517ba4.p0z14QAGlMfHRxN3gjR6MV7SqCZUWll-a2gy3-xluj8+ hash: v1.k794b7964.1b55ff7f599387807ca9aff238dd8d2cc8ed784aa5fb8beb47ea31ba8b96fb2b.T_EBsBIz2CPpYaKfoYjmDET7rVsOkbHJMdVeNiMEjcAscenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:- hash: v1.k794b7964.b587016659a8142a4ebf28da4bd7021f046f747ac69652fc2adf4a8999e036fc.GIus-c5aUlFGBDVpOk1Tzo4RVVAtqX0PIg9aFiM5m-g+ hash: v1.k794b7964.514a7dd8548054e3ba3509d30ea03050436ebda1778783ccea276a58796862bb.PIbqNZ6ihv-wOghiSKsPFBS2InXBWbZsN955dGwCRjQscenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:- hash: v1.k794b7964.2328b50f34a40d29439395b9d73e32952273850c2f693907ccd55fac4fa4c173.qNXMZjzpWCq9EWz5A_-XW2vqRJggFPjr0gi5vl1pKhM+ hash: v1.k794b7964.c616d9350a2e4dea4d69e032dc22f2f359d02944e5cef25564e1946946c665e6.cBr928anc4KbDbb3yI6SoeT6vgCwqIOLBpEYE3Zne1Iscenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:- hash: v1.k794b7964.89a1d706b8f7844cd7f6feb3e8f33ddd4c90c17a71a0d53e7ba41526747bf9f1.__f_Gvf5zJQZpaZYIQsQ5mVTVtoAOCw_skgfuJhBlFk+ hash: v1.k794b7964.24b439b90164ae7db044155845ca7672d56a4cba3114d585495e5dda13f24767.wjZpVrMTZpKpD3Ih75kZd7Q0gbrlPNB-GP22OYGTzZEscenes-app-data-warehouse-sql-editor--bi-saved-insight--light:- hash: v1.k794b7964.23e01cc0ea1a891915818180335099b4791cefe13366b23b5758ada24eb749d2.lAbew8pVJQoADw0B6vlstQ7g9zDX1TP4h-WmWtmWsqI+ hash: v1.k794b7964.a81476825e10522264b1bc91fdd971de2742ac5a58336132a16c5783d3341fb1.7U0EUeE-WqdHuHI4EedMwFE35R94newfE_FFgsD3Do4scenes-app-data-warehouse-sql-editor--edited-insight--dark:hash: v1.k794b7964.334b216a8359c768613cdec5b99a8a8ee26b6b5fac76397eaed8d6d1401a23c0.0pI7NMTufzUIfDel9Ngmhv3P3sdBu6IgpSj5xYNmYrYscenes-app-data-warehouse-sql-editor--edited-insight--light:diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 280aa1d3fe93..de7cf0d6e3f2 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -6155,6 +6155,20 @@},"type": "array"},+ "dateField": {+ "anyOf": [+ {+ "$ref": "#/definitions/BIField"+ },+ {+ "type": "null"+ }+ ],+ "description": "Column that receives the worksheet and dashboard date range."+ },+ "dateRange": {+ "$ref": "#/definitions/DateRange"+ },"filters": {"items": {"$ref": "#/definitions/BIFilter"diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.tsindex d96b9d5caf95..7b457077d993 100644--- a/frontend/src/queries/schema/schema-business-intelligence.ts+++ b/frontend/src/queries/schema/schema-business-intelligence.ts@@ -1,6 +1,14 @@import { ChartDisplayType } from '~/types'-import { ChartSettings, DatabaseSerializedFieldType, HogQLQuery, Node, NodeKind, TableSettings } from './schema-general'+import {+ ChartSettings,+ DatabaseSerializedFieldType,+ DateRange,+ HogQLQuery,+ Node,+ NodeKind,+ TableSettings,+} from './schema-general'export interface BIVisualizationNode extends Node<never> {kind: NodeKind.BIVisualizationNode@@ -71,6 +79,9 @@ export interface BIFilter {export interface BIConfig {source: BIDataSource | null+ /** Column that receives the worksheet and dashboard date range. */+ dateField?: BIField | null+ dateRange?: DateRangechartType: ChartDisplayTyperows: BIField[]columns: BIField[]diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex e6a2e2834314..a642775bf48c 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -2189,25 +2189,47 @@ describe('sqlEditorLogic', () => {})describe('open_view behavior', () => {- it('respects the requested output tab when opening a view from the URL', async () => {- logic = sqlEditorLogic({- tabId: TAB_ID,- monaco: createMockMonaco(),- editor: createMockEditor(),- })- logic.mount()+ it.each([undefined, { dateRange: { date_from: '-30d' } }])(+ 'restores saved view filters and the requested output tab with URL overrides %s',+ async (filters) => {+ const savedFilters = { dateRange: { date_from: '-7d' } }+ useMocks({+ get: {+ '/api/:scope/:team_id/warehouse_saved_queries/:id/': [+ 200,+ {+ ...MOCK_VIEW,+ query: { ...MOCK_VIEW.query, filters: savedFilters },+ },+ ],+ },+ })+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()- router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }, { output_tab: OutputTab.Results })+ router.actions.push(+ urls.sqlEditor(),+ { open_view: MOCK_VIEW.id },+ { output_tab: OutputTab.Results, ...(filters ? { filters } : {}) }+ )- await expectLogic(logic)- .toDispatchActions(['setViewLoading', 'createTab', 'updateTab'])- .toMatchValues({- editingView: partial({- id: MOCK_VIEW.id,- }),- outputActiveTab: OutputTab.Results,- })- })+ await expectLogic(logic)+ .toDispatchActions(['setViewLoading', 'createTab', 'updateTab'])+ .toMatchValues({+ editingView: partial({+ id: MOCK_VIEW.id,+ }),+ outputActiveTab: OutputTab.Results,+ })+ .toFinishAllListeners()+ expect(logic.values.sourceQuery.source.filters).toEqual(filters ?? savedFilters)+ expect(logic.values.hasEditorChanges).toBe(!!filters)+ }+ )it('preserves view details when a metadata list refresh updates the active tab', async () => {logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 35fbc5dd7ddb..dae14a751c8f 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -2081,7 +2081,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([insight,name: tabName,description: tabDescription,- sourceQuery: insightVisualizationQuery,+ sourceQuery: insightVisualizationQuery ?? (view ? hogQLEditorSourceQuery(view.query) : undefined),draft,metricName,biEditorState:@@ -2100,6 +2100,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})if (insightVisualizationQuery) {actions.setLastRunQuery(insightVisualizationQuery)+ } else if (view) {+ actions.setSourceQuery(hogQLEditorSourceQuery(view.query))}if (query !== undefined) {actions.setQueryInput(query)@@ -4003,6 +4005,9 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([} else {actions.editView(queryToOpen, view, biEditorStateFromUrl ?? undefined)}+ if (hasFiltersHashParam) {+ actions.setSourceQuery(applyFiltersFromUrl(values.sourceQuery))+ }actions.setViewLoading(false)actions.setViewQueryLoading(false)tabAdded = truediff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.pyindex 78b6fca8a889..377009e1a86b 100644--- a/posthog/hogql/filters.py+++ b/posthog/hogql/filters.py@@ -232,6 +232,10 @@ class ReplaceFilters(CloningVisitor):# {filters.breakdown(expr AS key, ...)} substitutes the column bound to the selected breakdown.if isinstance(node.expr, ast.ExprCall) and isinstance(node.expr.expr, ast.Field):call_chain = node.expr.expr.chain+ if call_chain == ["filters", "native"]:+ if len(node.expr.args) != 1:+ raise QueryError("{filters.native(expr)} requires one date expression or null.")+ return self._replace_native_filters(node.expr.args[0])if call_chain == ["filters", "interval"]:return self._replace_interval(node.expr.args)if call_chain == ["filters", "breakdown"]:@@ -247,93 +251,7 @@ class ReplaceFilters(CloningVisitor):no_filters = self.filters is None or not self.filters.model_fields_setif node.chain == ["filters"]:- last_select = self.selects[-1]- last_join = last_select.select_from- found_events = False- found_sessions = False- found_logs = False- found_traces = False- found_groups = False- found_persons = False- while last_join is not None:- if isinstance(last_join.table, ast.Field):- resolved = self._resolve_table(last_join.table.chain)- if isinstance(resolved, (EventsTable, AiEventsTable)):- found_events = True- if isinstance(resolved, SessionsTableV1 | SessionsTableV2 | SessionsTableV3):- found_sessions = True- if isinstance(resolved, (LogsTable, LogAttributesTable)):- found_logs = True- if isinstance(resolved, TraceSpansTable):- found_traces = True- if isinstance(resolved, GroupsTable):- found_groups = True- if isinstance(resolved, PersonsTable):- found_persons = True- if found_events and found_sessions or found_groups:- break- last_join = last_join.next_join-- if not any([found_events, found_sessions, found_logs, found_traces, found_groups, found_persons]):- raise QueryError(- f"Cannot use 'filters' placeholder in a SELECT clause that does not select from the events, sessions, logs, traces, groups or persons table."- )-- # Person semantics apply only when persons is the sole recognized table; any query that also- # touches an event-like table keeps its existing scope, so events-joined-to-persons insights- # are unaffected.- persons_only = found_persons and not any(- [found_events, found_sessions, found_logs, found_traces, found_groups]- )-- if no_filters:- return ast.Constant(value=True)-- assert self.filters is not None-- exprs: list[ast.Expr] = []- if self.filters.properties is not None:- if found_sessions:- session_properties = [p for p in self.filters.properties if isinstance(p, SessionPropertyFilter)]- non_session_properties = [- p for p in self.filters.properties if not isinstance(p, SessionPropertyFilter)- ]- if non_session_properties and not found_events:- raise QueryError(- "Can only use session properties in a filter when selecting from only the sessions table."- )- exprs.append(property_to_expr(session_properties, self.team, scope="session"))- exprs.append(property_to_expr(non_session_properties, self.team, scope="event"))- elif found_groups:- exprs.append(property_to_expr(self.filters.properties, self.team, scope="group"))- elif persons_only:- exprs.append(property_to_expr(self.filters.properties, self.team, scope="person"))- else:- exprs.append(property_to_expr(self.filters.properties, self.team, scope="event"))-- timestamp_field = ast.Field(chain=["$start_timestamp"])- if found_events or found_logs or found_traces:- timestamp_field = ast.Field(chain=["timestamp"])- if found_groups or persons_only:- timestamp_field = ast.Field(chain=["created_at"])-- exprs.extend(self._date_range_exprs(timestamp_field))-- if self.filters.filterTestAccounts:- for prop in self.team.test_account_filters or []:- if persons_only:- try:- exprs.append(property_to_expr(prop, self.team, scope="person"))- except (QueryError, NotImplementedError) as error:- raise self._persons_test_account_filter_error(prop) from error- else:- exprs.append(property_to_expr(prop, self.team, scope="event"))-- if len(exprs) == 0:- return ast.Constant(value=True)- if len(exprs) == 1:- return exprs[0]- return ast.And(exprs=exprs)+ return self._replace_native_filters()if node.chain == ["filters", "dateRange", "from"]:compare_op_wrapper = self.compare_operations[-1]@@ -385,6 +303,97 @@ class ReplaceFilters(CloningVisitor):return super().visit_placeholder(node)+ def _replace_native_filters(self, timestamp_override: ast.Expr | None = None) -> ast.Expr:+ last_select = self.selects[-1]+ last_join = last_select.select_from+ found_events = False+ found_sessions = False+ found_logs = False+ found_traces = False+ found_groups = False+ found_persons = False+ while last_join is not None:+ if isinstance(last_join.table, ast.Field):+ resolved = self._resolve_table(last_join.table.chain)+ if isinstance(resolved, (EventsTable, AiEventsTable)):+ found_events = True+ if isinstance(resolved, SessionsTableV1 | SessionsTableV2 | SessionsTableV3):+ found_sessions = True+ if isinstance(resolved, (LogsTable, LogAttributesTable)):+ found_logs = True+ if isinstance(resolved, TraceSpansTable):+ found_traces = True+ if isinstance(resolved, GroupsTable):+ found_groups = True+ if isinstance(resolved, PersonsTable):+ found_persons = True+ if found_events and found_sessions or found_groups:+ break+ last_join = last_join.next_join++ if not any([found_events, found_sessions, found_logs, found_traces, found_groups, found_persons]):+ raise QueryError(+ f"Cannot use 'filters' placeholder in a SELECT clause that does not select from the events, sessions, logs, traces, groups or persons table."+ )++ # Person semantics apply only when persons is the sole recognized table; any query that also+ # touches an event-like table keeps its existing scope, so events-joined-to-persons insights+ # are unaffected.+ persons_only = found_persons and not any([found_events, found_sessions, found_logs, found_traces, found_groups])++ if self.filters is None or not self.filters.model_fields_set:+ return ast.Constant(value=True)++ assert self.filters is not None++ exprs: list[ast.Expr] = []+ if self.filters.properties is not None:+ if found_sessions:+ session_properties = [p for p in self.filters.properties if isinstance(p, SessionPropertyFilter)]+ non_session_properties = [+ p for p in self.filters.properties if not isinstance(p, SessionPropertyFilter)+ ]+ if non_session_properties and not found_events:+ raise QueryError(+ "Can only use session properties in a filter when selecting from only the sessions table."+ )+ exprs.append(property_to_expr(session_properties, self.team, scope="session"))+ exprs.append(property_to_expr(non_session_properties, self.team, scope="event"))+ elif found_groups:+ exprs.append(property_to_expr(self.filters.properties, self.team, scope="group"))+ elif persons_only:+ exprs.append(property_to_expr(self.filters.properties, self.team, scope="person"))+ else:+ exprs.append(property_to_expr(self.filters.properties, self.team, scope="event"))++ timestamp_field = ast.Field(chain=["$start_timestamp"])+ if found_events or found_logs or found_traces:+ timestamp_field = ast.Field(chain=["timestamp"])+ if found_groups or persons_only:+ timestamp_field = ast.Field(chain=["created_at"])++ if timestamp_override is not None:+ if not (isinstance(timestamp_override, ast.Constant) and timestamp_override.value is None):+ exprs.extend(self._date_range_exprs(timestamp_override))+ else:+ exprs.extend(self._date_range_exprs(timestamp_field))++ if self.filters.filterTestAccounts:+ for prop in self.team.test_account_filters or []:+ if persons_only:+ try:+ exprs.append(property_to_expr(prop, self.team, scope="person"))+ except (QueryError, NotImplementedError) as error:+ raise self._persons_test_account_filter_error(prop) from error+ else:+ exprs.append(property_to_expr(prop, self.team, scope="event"))++ if len(exprs) == 0:+ return ast.Constant(value=True)+ if len(exprs) == 1:+ return exprs[0]+ return ast.And(exprs=exprs)+def _replace_bound_filters(self, call: ast.Call) -> ast.Expr:# Parse bindings before the no-filters early return, so malformed usage surfaces in the# SQL editor even while no filter is set yet.diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.pyindex c498630cdad7..3cdb1fed8372 100644--- a/posthog/hogql/test/test_filters.py+++ b/posthog/hogql/test/test_filters.py@@ -663,6 +663,22 @@ class TestFilters(BaseTest):):replace_filters(select, HogQLFilters(), self.team)+ @parameterized.expand([("none", "null"), ("custom", "created_at")])+ def test_native_filters_preserve_properties_with_custom_date_column(self, _name: str, expression: str) -> None:+ query = self._parse_select("SELECT event FROM events WHERE {filters.native(" + expression + ")}")+ filters = HogQLFilters(+ dateRange=DateRange(date_from="2026-01-01", date_to="2026-01-31"),+ properties=[EventPropertyFilter(key="plan", value="pro", operator="exact")],+ )+ sql = self._print_ast(replace_filters(query, filters, self.team))+ assert "properties.plan" in sql and "'pro'" in sql+ assert "timestamp" not in sql+ if expression == "null":+ assert "2026-01" not in sql+ else:+ assert "greaterOrEquals(created_at" in sql+ assert "2026-01-01" in sql and "2026-01-31" in sql+def test_bound_filters_date_range_and_property(self):# persons is a table the plain {filters} placeholder rejects, so this exercises the unlockwith time_machine.travel("2020-02-15T13:37:42Z", tick=False):diff --git a/posthog/hogql_queries/test/test_hogql_dashboard_filters.py b/posthog/hogql_queries/test/test_hogql_dashboard_filters.pyindex 3e33f4ad4b19..5a01dc0d1cf7 100644--- a/posthog/hogql_queries/test/test_hogql_dashboard_filters.py+++ b/posthog/hogql_queries/test/test_hogql_dashboard_filters.py@@ -15,6 +15,9 @@ from posthog.schema import (IntervalType,)+from posthog.hogql.context import HogQLContext+from posthog.hogql.printer import prepare_and_print_ast+from posthog.hogql_queries.apply_dashboard_filters import (apply_dashboard_filters,apply_dashboard_filters_to_dict,@@ -63,6 +66,33 @@ class TestHogQLDashboardFilters(BaseTest):assert updated.source.variables["plan"].value == "enterprise"assert updated.source.variables["plan"].code_name == "plan"+ @parameterized.expand(+ [+ ("native", "{filters}"),+ ("bound", "{filters(timestamp AS timestamp, properties.plan AS 'plan')}"),+ ]+ )+ def test_bi_dashboard_filters_reach_the_query(self, _name: str, placeholder: str) -> None:+ runner = self._create_hogql_runner(+ query="SELECT count() FROM events WHERE " + placeholder + " AND event = 'purchase'",+ filters=HogQLFilters(dateRange=DateRange(date_from="-7d")),+ )+ runner.apply_dashboard_filters(+ DashboardFilter(+ date_from="2026-01-01",+ date_to="2026-01-31",+ properties=[EventPropertyFilter(key="plan", value="pro", operator="exact")],+ )+ )+ sql = prepare_and_print_ast(+ runner.to_query(), dialect="hogql", context=HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ )[0]+ assert "2026-01-01" in sql+ assert "2026-01-31" in sql+ assert "plan" in sql and "'pro'" in sql+ assert "equals(event, 'purchase')" in sql+ assert "{filters" not in sql+def _create_hogql_runner(self, query: str = "SELECT uuid FROM events", filters: Optional[HogQLFilters] = None) -> HogQLQueryRunner:diff --git a/posthog/schema.py b/posthog/schema.pyindex 4ba26960f9f6..9ae6938fdbd2 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -11071,6 +11071,11 @@ class BIConfig(BaseModel):)chartType: ChartDisplayTypecolumns: list[BIField]+ dateField: BIField | None = Field(+ default=None,+ description="Column that receives the worksheet and dashboard date range.",+ )+ dateRange: DateRange | None = Nonefilters: list[BIFilter]limit: BIQueryLimitrows: list[BIField]diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.tsindex 2d982acbd352..7a3fd7bdd1b3 100644--- a/products/business_intelligence/frontend/biEditorLogic.ts+++ b/products/business_intelligence/frontend/biEditorLogic.ts@@ -15,7 +15,7 @@ import {BIQueryLimit,BISort,} from '~/queries/schema/schema-business-intelligence'-import { DatabaseSchemaTable } from '~/queries/schema/schema-general'+import { DatabaseSchemaTable, DateRange } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'import { captureBIEditorModeSelected } from 'products/business_intelligence/frontend/biEditorAnalytics'@@ -41,6 +41,8 @@ import {normalizeBIConfig,} from 'products/business_intelligence/frontend/biEditorTypes'+import { getBIDateField } from './biQueryFilters'+export interface BIEditorLogicProps {tabId: string}@@ -77,7 +79,9 @@ function setDataSourceInConfig(config: BIConfig, source: BIDataSource): BIConfigrows: [],columns: [],values: [],- filters: defaultDateFilter ? [defaultDateFilter] : [],+ filters: [],+ dateField: defaultDateFilter?.field ?? getBIDateField({ ...config, source, dateField: undefined }),+ dateRange: { date_from: defaultDateFilter ? '-7d' : 'all' },sort: null,}}@@ -349,6 +353,12 @@ export interface biEditorLogicActions {setDataSource: (source: BIDataSource) => {source: BIDataSource}+ setDateField: (field: BIField | null) => {+ field: BIField | null+ }+ setDateRange: (dateRange: DateRange) => {+ dateRange: DateRange+ }setEditorView: (editorView: BIEditorView) => {editorView: BIEditorView}@@ -518,6 +528,8 @@ export const biEditorLogic = kea<biEditorLogicType>([target,}),setChartType: (chartType: ChartDisplayType) => ({ chartType }),+ setDateRange: (dateRange: DateRange) => ({ dateRange }),+ setDateField: (field: BIField | null) => ({ field }),setDataSource: (source: BIDataSource) => ({ source }),setValueAggregation: (index: number, aggregation: BIAggregation) => ({ index, aggregation }),setFilterOperator: (index: number, operator: BIFilterOperator) => ({ index, operator }),@@ -637,6 +649,8 @@ export const biEditorLogic = kea<biEditorLogicType>([swapRowsAndColumns: (config) =>normalizeBIConfig({ ...config, rows: config.columns, columns: config.rows }),setChartType: (config, { chartType }) => normalizeBIConfig({ ...config, chartType }),+ setDateRange: (config, { dateRange }) => ({ ...config, dateRange }),+ setDateField: (config, { field }) => ({ ...config, dateField: field }),setDataSource: (config, { source }) => setDataSourceInConfig(config, source),setValueAggregation: (config, { index, aggregation }) => ({...config,@@ -823,6 +837,8 @@ export const biEditorLogic = kea<biEditorLogicType>([addBlankFieldToShelf: () => actions.runAfterChange(),removeFieldFromShelf: () => actions.runAfterChange(),setChartType: () => actions.runAfterChange(),+ setDateRange: () => actions.runAfterChange(),+ setDateField: () => actions.runAfterChange(),setDataSource: () => actions.runAfterChange(),setValueAggregation: () => actions.runAfterChange(),setFilterOperator: () => actions.runAfterChange(),diff --git a/products/business_intelligence/frontend/biEditorOptions.tsx b/products/business_intelligence/frontend/biEditorOptions.tsxindex e835c3581347..fc5100992e0e 100644--- a/products/business_intelligence/frontend/biEditorOptions.tsx+++ b/products/business_intelligence/frontend/biEditorOptions.tsx@@ -3,12 +3,22 @@ import { IconGraph, IconLifecycle, IconMagicWand, IconPieChart, IconPulse, IconTimport { FEATURE_FLAGS } from 'lib/constants'import { Icon123, IconAreaChart, IconDonutChart, IconHeatmap, IconTableChart } from 'lib/lemon-ui/icons'import { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { dateMapping } from 'lib/utils/dateFilters'import { BIAggregation, BIDateBucket, BIFilterOperator } from '~/queries/schema/schema-business-intelligence'-import { ChartDisplayType } from '~/types'+import { ChartDisplayType, DateMappingOption } from '~/types'import { BI_QUERY_LIMITS } from 'products/business_intelligence/frontend/biEditorTypes'+export const BI_DATE_OPTIONS: DateMappingOption[] = [+ ...dateMapping+ .filter((option) => option.key !== 'All time')+ .map((option) => (option.key === 'This year' ? { ...option, key: 'Year to date' } : option)),+ { key: 'This quarter', values: ['qStart'], defaultInterval: 'week' },+ { key: 'Last quarter', values: ['-1qStart', '-1qEnd'], defaultInterval: 'week' },+ { key: 'All time', values: ['all'], defaultInterval: 'month' },+]+export const CHART_TYPE_OPTIONS: { value: ChartDisplayType; label: string; icon: JSX.Element }[] = [{ value: ChartDisplayType.Auto, label: 'Automatic', icon: <IconMagicWand /> },{ value: ChartDisplayType.ActionsTable, label: 'Table', icon: <IconTableChart /> },diff --git a/products/business_intelligence/frontend/biEditorTypes.test.ts b/products/business_intelligence/frontend/biEditorTypes.test.tsindex b215b2f1e505..601b932df995 100644--- a/products/business_intelligence/frontend/biEditorTypes.test.ts+++ b/products/business_intelligence/frontend/biEditorTypes.test.ts@@ -63,6 +63,53 @@ const countryField: BIField = {}describe('BI editor query generation', () => {+ test.each(['-28d', 'mStart', '-1mStart', 'qStart', '-1qStart', 'yStart'])(+ 'keeps %s relative in query filters instead of hardcoding the date in SQL',+ (date_from) => {+ const config = { ...DEFAULT_BI_CONFIG, source: eventField.source, dateRange: { date_from } }+ const result = buildBIQuery(config)!+ expect(result.query).toContain('WHERE\n {filters}')+ expect(result.query).not.toContain(date_from)+ expect(result.node.source.filters?.dateRange).toEqual({ date_from })+ expect(parseBIEditorState(BIEditorView.BI, config)?.config.dateRange).toEqual({+ date_from,+ })+ }+ )++ it.each([null, { ...timestampField, expression: 'created_at' }])(+ 'keeps native properties with a custom date selection: %j',+ (dateField) => {+ const result = buildBIQuery({ ...DEFAULT_BI_CONFIG, source: eventField.source, dateField })!+ expect(result.query).toContain(`{filters.native(${dateField?.expression ?? 'null'})}`)+ }+ )++ it('binds raw property names, including dots, without silently choosing ambiguous columns', () => {+ const source = { table: 'orders' }+ const field = { ...eventField, source, name: 'properties.plan.tier', expression: 'properties.`plan.tier`' }+ const state = { ...DEFAULT_BI_CONFIG, source, rows: [field] }+ expect(buildBIQuery(state)?.query).toContain("(properties.`plan.tier`) AS 'plan.tier'")+ const ambiguous = buildBIQuery({+ ...state,+ columns: [{ ...field, name: 'person_properties.plan.tier', expression: 'person_properties.`plan.tier`' }],+ })!+ expect(ambiguous.query).not.toContain("AS 'plan.tier'")+ })++ it('maps warehouse dates and dashboard properties to unbucketed worksheet fields', () => {+ const source = { table: 'orders', connectionId: 'example-connection' }+ const result = buildBIQuery({+ ...DEFAULT_BI_CONFIG,+ source,+ dateField: { ...timestampField, source, expression: 'created_at', dateBucket: 'month' },+ dateRange: { date_from: '-30d' },+ rows: [{ ...eventField, source, name: 'plan', expression: 'subscription_plan' }],+ })!+ expect(result.query).toContain("{filters((created_at) AS 'timestamp', (subscription_plan) AS 'plan')}")+ expect(result.node.source.connectionId).toBe(source.connectionId)+ expect(result.node.source.filters?.dateRange?.date_from).toBe('-30d')+ })test.each<{ filter: BIFilter; expected: string | null }>([{filter: { field: eventField, operator: 'in', value: '', values: ["sign'up", 'a,b', ''] },@@ -121,9 +168,9 @@ describe('BI editor query generation', () => {expect(restored?.config.filters).toEqual([filter])const query = buildBIQuery(restored!.config)!.queryif (expected) {- expect(query).toContain(`WHERE\n ${expected}`)+ expect(query).toContain(`AND (${expected})`)} else {- expect(query).not.toContain('WHERE')+ expect(query).toContain('WHERE\n {filters}\nLIMIT')}})@@ -162,7 +209,8 @@ describe('BI editor query generation', () => {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',+ filters: { dateRange: { date_from: 'all' } },+ query: "SELECT DISTINCT toString(event) AS value\nFROM orders\nWHERE ({filters((null) AS 'timestamp', (event) AS 'event', (properties.revenue) AS 'revenue')}) AND (event IS NOT NULL) AND ((properties.revenue >= 10 AND properties.revenue <= 100))\nLIMIT 100",})config.filters.push({field: { ...eventField, expression: '', name: '', source },@@ -193,7 +241,8 @@ describe('BI editor query generation', () => {' sum(properties.revenue) AS sum_revenue','FROM events','WHERE',- " lower(event) LIKE lower('%sign\\'up%')",+ ' {filters}',+ " AND (lower(event) LIKE lower('%sign\\'up%'))",'GROUP BY',' event','ORDER BY',@@ -218,6 +267,7 @@ describe('BI editor query generation', () => {kind: NodeKind.HogQLQuery,query: expectedQuery,connectionId: undefined,+ filters: { dateRange: { date_from: 'all' } },},display: ChartDisplayType.ActionsBar,},@@ -348,7 +398,9 @@ describe('BI editor query generation', () => {limit: 100,})- expect(result?.query).toEqual(['SELECT', ' count(*) AS count', 'FROM events', 'LIMIT 100'].join('\n'))+ expect(result?.query).toEqual(+ ['SELECT', ' count(*) AS count', 'FROM events', 'WHERE', ' {filters}', 'LIMIT 100'].join('\n')+ )})it('uses a row count when a custom aggregation expression is blank', () => {@@ -368,6 +420,8 @@ describe('BI editor query generation', () => {' event,',' count(*) AS count','FROM events',+ 'WHERE',+ ' {filters}','GROUP BY',' event','ORDER BY',@@ -484,8 +538,8 @@ describe('BI editor query generation', () => {expect(createDefaultDateFilter(source)).toBeNull()})- it('bounds the default last 7 days condition at the current time', () => {- const result = buildBIQuery({+ it('migrates the legacy default date filter into dashboard-aware query filters', () => {+ const config: BIConfig = {source: { table: 'events' },chartType: ChartDisplayType.Auto,rows: [],@@ -493,9 +547,13 @@ describe('BI editor query generation', () => {values: [],filters: [createDefaultDateFilter({ table: 'events' })!],limit: 100,- })+ }+ const result = buildBIQuery(config)- expect(result?.query).toContain('(timestamp >= now() - INTERVAL 7 DAY AND timestamp < now())')+ expect(result?.query).toContain('{filters}')+ expect(result?.query).not.toContain('INTERVAL 7 DAY')+ expect(result?.node.source.filters?.dateRange).toEqual({ date_from: '-7d' })+ expect(parseBIEditorState(BIEditorView.BI, config)?.config.filters).toEqual([])})test.each([diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.tsindex d85e631cbae7..5e722b346377 100644--- a/products/business_intelligence/frontend/biEditorTypes.ts+++ b/products/business_intelligence/frontend/biEditorTypes.ts@@ -28,6 +28,8 @@ import {} from '~/queries/utils'import { ChartDisplayType } from '~/types'+import { getBIFiltersPlaceholder, getBIQueryFilters, normalizeBIDates } from './biQueryFilters'+export enum BIEditorView {SQL = 'sql',BI = 'bi',@@ -122,7 +124,7 @@ export const DEFAULT_BI_CONFIG: BIConfig = {}export function normalizeBIConfig(config: BIConfig): BIConfig {- let normalized = config+ let normalized = normalizeBIDates(config)const sort = normalized.sortif (sort && !getBISortOptions(normalized).some((option) => option.key === sort.key)) {normalized = { ...normalized, sort: null }@@ -425,6 +427,20 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow}const candidate = decodedConfig as Partial<BIConfig>+ if (+ candidate.dateRange !== undefined &&+ (!candidate.dateRange ||+ typeof candidate.dateRange !== 'object' ||+ [candidate.dateRange.date_from, candidate.dateRange.date_to].some(+ (bound) => bound != null && typeof bound !== 'string'+ ) ||+ (candidate.dateRange.explicitDate !== undefined && typeof candidate.dateRange.explicitDate !== 'boolean'))+ ) {+ return null+ }+ if (candidate.dateField !== undefined && candidate.dateField !== null && !parseBIFieldValue(candidate.dateField)) {+ return null+ }const source =candidate.source === null? null@@ -520,6 +536,10 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknowconst config: BIConfig = {source,+ ...(candidate.dateField !== undefined+ ? { dateField: candidate.dateField === null ? null : parseBIFieldValue(candidate.dateField) }+ : {}),+ ...(candidate.dateRange !== undefined ? { dateRange: candidate.dateRange } : {}),chartType: candidate.chartType as ChartDisplayType,rows: rows as BIField[],columns: columns as BIField[],@@ -533,6 +553,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow...config.columns,...config.values.map((value) => value.field),...config.filters.map((filter) => filter.field),+ ...(config.dateField ? [config.dateField] : []),]if (fields.length > 0 && (!source || fields.some((field) => !isBIFieldCompatible(source, field)))) {@@ -749,6 +770,7 @@ function filterExpression(filter: BIFilter): string | null {}export function buildBIFilterOptionsQuery(config: BIConfig, index: number): HogQLQuery | null {+ config = normalizeBIConfig(config)const filter = config.filters[index]if (!config.source ||@@ -769,7 +791,8 @@ export function buildBIFilterOptionsQuery(config: BIConfig, index: number): HogQreturn {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`,+ filters: getBIQueryFilters(config),+ query: `SELECT DISTINCT toString(${expression}) AS value\nFROM ${escapePropertyAsHogQLIdentifier(config.source.table)}\nWHERE ${[getBIFiltersPlaceholder(config), `${expression} IS NOT NULL`, ...conditions].map((condition) => `(${condition})`).join(' AND ')}\nLIMIT 100`,}}@@ -964,6 +987,7 @@ function buildOrderByExpression(}export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {+ config = normalizeBIConfig(config)if (!config.source || config.filters.some(getBIFilterValidationError)) {return null}@@ -1011,9 +1035,9 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {`FROM ${escapePropertyAsHogQLIdentifier(config.source.table)}`,]- if (filters.length > 0) {- queryParts.push(`WHERE\n ${filters.join('\n AND ')}`)- }+ queryParts.push(+ `WHERE\n ${[getBIFiltersPlaceholder(config), ...filters.map((filter) => `(${filter})`)].join('\n AND ')}`+ )if (dimensionExpressions.length > 0) {queryParts.push(`GROUP BY\n ${dimensionExpressions.join(',\n ')}`)}@@ -1064,6 +1088,8 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {kind: NodeKind.HogQLQuery,query,connectionId: config.source.connectionId,+ sendRawQuery: undefined,+ filters: getBIQueryFilters(config),},display: config.chartType,...(pivotTableSettings || seriesSettings ? { chartSettings: pivotTableSettings ?? seriesSettings } : {}),diff --git a/products/business_intelligence/frontend/biQueryFilters.ts b/products/business_intelligence/frontend/biQueryFilters.tsnew file mode 100644index 000000000000..515f286e80e5--- /dev/null+++ b/products/business_intelligence/frontend/biQueryFilters.ts@@ -0,0 +1,96 @@+import { BIConfig, BIDataSource, BIField } from '~/queries/schema/schema-business-intelligence'+import { DateRange, HogQLFilters, HogQLQuery } from '~/queries/schema/schema-general'+import { escapeHogQLString } from '~/queries/utils'++const NATIVE_DATE_FIELDS: Record<string, string> = {+ events: 'timestamp',+ ai_events: 'timestamp',+ sessions: '$start_timestamp',+ persons: 'created_at',+ groups: 'created_at',+ logs: 'timestamp',+ traces: 'timestamp',+}++export function getBIDateField(config: BIConfig): BIField | null {+ if (config.dateField !== undefined) {+ return config.dateField+ }+ const source = config.source+ const expression = source && !source.connectionId ? NATIVE_DATE_FIELDS[source.table] : undefined+ return source && expression+ ? { id: `bi-date:${source.table}:${expression}`, name: expression, expression, type: 'datetime', source }+ : null+}++export function usesNativeBIFilters(source: BIDataSource | null): boolean {+ return !!source && !source.connectionId && !!NATIVE_DATE_FIELDS[source.table]+}++export function normalizeBIDates(config: BIConfig): BIConfig {+ if (config.dateRange !== undefined) {+ return config+ }+ const legacy = config.filters.find(+ (filter) => filter.field.id.startsWith('bi-default:') && filter.operator === 'last_7_days'+ )+ return legacy+ ? {+ ...config,+ dateField: legacy.field,+ dateRange: { date_from: legacy.enabled === false ? 'all' : '-7d' },+ filters: config.filters.filter((filter) => filter !== legacy),+ }+ : config+}++export function getBIFiltersPlaceholder(config: BIConfig): string {+ const dateField = getBIDateField(config)+ if (usesNativeBIFilters(config.source)) {+ return dateField?.expression === NATIVE_DATE_FIELDS[config.source!.table]+ ? '{filters}'+ : `{filters.native(${dateField?.expression || 'null'})}`+ }+ const bindings = new Map<string, string>([['timestamp', dateField?.expression || 'null']])+ const ambiguous = new Set<string>()+ for (const field of [+ ...config.rows,+ ...config.columns,+ ...config.values.map((value) => value.field),+ ...config.filters.map((filter) => filter.field),+ ]) {+ const propertyKey = field.name.replace(/^(?:.*\.)?(?:properties|person_properties)\./, '')+ for (const key of new Set([field.name, propertyKey])) {+ if (!key || key === 'timestamp' || !field.expression.trim() || ambiguous.has(key)) {+ continue+ }+ if (bindings.has(key) && bindings.get(key) !== field.expression) {+ bindings.delete(key)+ ambiguous.add(key)+ } else {+ bindings.set(key, field.expression)+ }+ }+ }+ return `{filters(${[...bindings].map(([key, expression]) => `(${expression}) AS ${escapeHogQLString(key)}`).join(', ')})}`+}++export function getBIQueryFilters(config: BIConfig, filters?: HogQLFilters): HogQLFilters {+ return { ...filters, dateRange: config.dateRange ?? { date_from: 'all' } }+}++export function mergeBIQuerySource(current: HogQLQuery, generated: HogQLQuery): HogQLQuery {+ return { ...current, ...generated, filters: { ...current.filters, ...generated.filters } }+}++export function applyBIDateRange(config: BIConfig, dateRange: DateRange | undefined): BIConfig {+ if (+ !dateRange ||+ ((config.dateRange?.date_from ?? 'all') === (dateRange.date_from ?? 'all') &&+ (config.dateRange?.date_to ?? null) === (dateRange.date_to ?? null) &&+ !!config.dateRange?.explicitDate === !!dateRange.explicitDate)+ ) {+ return config+ }+ return { ...config, dateRange }+}diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.tsindex 7bd96eeaa7a1..d24178e9e50b 100644--- a/products/business_intelligence/frontend/biSceneLogic.test.ts+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts@@ -7,9 +7,9 @@ import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'-import { DatabaseSchemaQuery, NodeKind } from '~/queries/schema/schema-general'+import { DatabaseSchemaQuery, HogQLFilters, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { ChartDisplayType } from '~/types'+import { ChartDisplayType, PropertyFilterType, PropertyOperator } from '~/types'import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'@@ -33,6 +33,7 @@ const timestampField: BIField = {}const config: BIConfig = {source: { table: 'events' },+ dateRange: { date_from: 'all' },chartType: ChartDisplayType.ActionsBar,rows: [eventField],columns: [timestampField],@@ -164,6 +165,8 @@ describe('biSceneLogic', () => {editor.actions.setChartType(ChartDisplayType.ActionsStackedBar)expect(logic.values.hasUnsavedChanges).toBe(true)expect(logic.values.worksheet.chartSettings?.yAxis?.[0].settings?.formatting?.prefix).toBe('$')+ editor.actions.setDateRange({ date_from: '-30d' })+ expect(logic.values.worksheet.chartSettings?.yAxis?.[0].settings?.formatting?.prefix).toBe('$')logic.actions.discardChanges()expect(logic.values.worksheet.config).toEqual(config)expect(logic.values.hasUnsavedChanges).toBe(false)@@ -182,6 +185,43 @@ describe('biSceneLogic', () => {expect(save).not.toHaveBeenCalled()})+ it('preserves an unfinished calculated measure when chart settings update', () => {+ logic.actions.restoreWorksheet(worksheet())+ editor.actions.setCalculatedMeasureDraft({+ index: null,+ name: 'Revenue per user',+ expression: 'sum(revenue) /',+ })+ const draft = editor.values.calculatedMeasureDraft+ logic.actions.setVisualization({ ...logic.values.worksheet, tableSettings: { conditionalFormatting: [] } })+ expect(editor.values.calculatedMeasureDraft).toEqual(draft)+ })++ it('reruns unchanged SQL for a date change while preserving dashboard properties', async () => {+ const properties: HogQLFilters['properties'] = [+ { type: PropertyFilterType.Event, key: 'plan', value: 'pro', operator: PropertyOperator.Exact },+ ]+ const node = worksheet()+ node.source.filters = { dateRange: { date_from: '-7d' }, properties }+ logic.actions.restoreWorksheet(node)+ expect(editor.values.config.dateRange).toEqual({ date_from: '-7d' })+ const sql = logic.values.worksheet.source.query+ const data = dataNodeLogic({ key: logic.values.dataNodeKey, query: node.source, autoLoad: false })+ data.mount()+ data.actions.setResponse({ results: [[1]], columns: ['count'], types: [['count', 'Int64']] })+ jest.useFakeTimers()+ try {+ editor.actions.setAutoUpdate(true)+ editor.actions.setDateRange({ date_from: '-30d' })+ await jest.advanceTimersByTimeAsync(500)+ expect(logic.values.lastRunQuery?.source.query).toBe(sql)+ expect(logic.values.lastRunQuery?.source.filters).toEqual({ dateRange: { date_from: '-30d' }, properties })+ } finally {+ jest.useRealTimers()+ data.unmount()+ }+ })+it('restores legacy BI links and persists edits as a wrapper', async () => {router.actions.push(urls.businessIntelligence(), {}, { q: 'SELECT event FROM events', bi: config, mode: 'bi' })await expectLogic(databaseTableListLogic).toFinishAllListeners()diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.tsindex 89b3ef178fea..f5df2dd30567 100644--- a/products/business_intelligence/frontend/biSceneLogic.ts+++ b/products/business_intelligence/frontend/biSceneLogic.ts@@ -50,6 +50,7 @@ import {parseBIEditorState,} from './biEditorTypes'import type { BIQueryBuildResult } from './biEditorTypes'+import { applyBIDateRange, mergeBIQuerySource } from './biQueryFilters'export interface BISceneLogicProps {tabId: string@@ -345,7 +346,9 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicTypekind: NodeKind.BIVisualizationNode,config,display: config.chartType,- source: { ...visualization.source, ...(generatedQuery?.node.source ?? { query: '' }) },+ source: generatedQuery+ ? mergeBIQuerySource(visualization.source, generatedQuery.node.source)+ : { ...visualization.source, query: '' },chartSettings: mergeBIChartSettings(visualization.chartSettings, generatedQuery?.node.chartSettings),}),],@@ -404,7 +407,10 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicTypeif (connectionChanged) {databaseTableListLogic.actions.setConnection(connectionId)}- actions.restoreState({ editorView: BIEditorView.BI, config: worksheet.config })+ actions.restoreState({+ editorView: BIEditorView.BI,+ config: applyBIDateRange(worksheet.config, worksheet.source.filters?.dateRange),+ })if (connectionChanged || !databaseTableListLogic.values.database) {databaseTableListLogic.actions.loadDatabase({ shallow: true })}@@ -483,6 +489,10 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType},cancelQuery: () => dataNodeLogic.findMounted({ key: values.dataNodeKey })?.actions.cancelQuery(),setVisualization: ({ visualization }) => {+ const config = applyBIDateRange(values.config, visualization.source.filters?.dateRange)+ if (config !== values.config) {+ actions.restoreState({ editorView: BIEditorView.BI, config })+ }if (visualization.display && visualization.display !== values.config.chartType) {actions.setChartType(visualization.display)}diff --git a/products/business_intelligence/frontend/components/BIDateControls.tsx b/products/business_intelligence/frontend/components/BIDateControls.tsxnew file mode 100644index 000000000000..c2a9812eb305--- /dev/null+++ b/products/business_intelligence/frontend/components/BIDateControls.tsx@@ -0,0 +1,62 @@+import { useActions, useValues } from 'kea'++import { IconCalendar } from '@posthog/icons'+import { LemonSelect } from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'++import { biEditorLogic } from '../biEditorLogic'+import { BI_DATE_OPTIONS } from '../biEditorOptions'+import { isDateTimeBIField } from '../biEditorTypes'+import { getBIDateField } from '../biQueryFilters'++export function BIDateControls(): JSX.Element {+ const { config, dataPaneFields } = useValues(biEditorLogic)+ const { setDateField, setDateRange } = useActions(biEditorLogic)+ const dateField = getBIDateField(config)+ const dateFields = dataPaneFields.dimensions.filter(isDateTimeBIField)+ if (dateField && !dateFields.some((field) => field.expression === dateField.expression)) {+ dateFields.unshift(dateField)+ }++ return (+ <div className="flex flex-wrap items-center gap-1" data-attr="bi-editor-date-controls">+ <LemonSelect+ size="small"+ type="tertiary"+ value={dateField?.expression ?? null}+ options={[+ { value: null, label: 'No date column' },+ ...dateFields.map((field) => ({ value: field.expression, label: field.name })),+ ]}+ onChange={(expression) =>+ setDateField(dateFields.find((field) => field.expression === expression) ?? null)+ }+ renderButtonContent={(option) => `Date: ${option?.label}`}+ tooltip="The dashboard date range applies to this column and overrides the worksheet range."+ aria-label="Dashboard date column"+ data-attr="bi-editor-date-field"+ />+ <DateFilter+ size="small"+ type="tertiary"+ dateFrom={config.dateRange?.date_from ?? 'all'}+ dateTo={config.dateRange?.date_to ?? null}+ explicitDate={config.dateRange?.explicitDate ?? false}+ onChange={(date_from, date_to, explicitDate) => setDateRange({ date_from, date_to, explicitDate })}+ disabledReason={!dateField ? 'Select a date column first' : undefined}+ dateOptions={BI_DATE_OPTIONS}+ allowedRollingDateOptions={['hours', 'days', 'weeks', 'months', 'years']}+ allowTimePrecision+ allowFixedRangeWithTime+ showExplicitDateToggle+ makeLabel={(label) => (+ <>+ <IconCalendar />+ <span>{label}</span>+ </>+ )}+ />+ </div>+ )+}diff --git a/products/business_intelligence/frontend/components/BIToolbar.tsx b/products/business_intelligence/frontend/components/BIToolbar.tsxindex a76b5d7c5e84..a25d2c0c7c5c 100644--- a/products/business_intelligence/frontend/components/BIToolbar.tsx+++ b/products/business_intelligence/frontend/components/BIToolbar.tsx@@ -13,6 +13,8 @@ import { LIMIT_OPTIONS } from 'products/business_intelligence/frontend/biEditorOimport { biSceneLogic } from 'products/business_intelligence/frontend/biSceneLogic'import { BIShowMe } from 'products/business_intelligence/frontend/components/BIShowMe'+import { BIDateControls } from './BIDateControls'+export function BIToolbar(): JSX.Element {const editor = useMountedLogic(biEditorLogic)const scene = biSceneLogic({ tabId: editor.props.tabId })@@ -118,6 +120,8 @@ export function BIToolbar(): JSX.Element {data-attr="bi-editor-query-limit"/><LemonDivider vertical />+ <BIDateControls />+ <LemonDivider vertical /><LemonButtonsize="small"type="tertiary"diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 44badec48632..9ddb9c251cc0 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -9338,6 +9338,9 @@ export interface BIValueApi {export interface BIConfigApi {chartType: ChartDisplayTypeApicolumns: BIFieldApi[]+ /** Column that receives the worksheet and dashboard date range. */+ dateField?: BIFieldApi | null+ dateRange?: DateRangeApi | nullfilters: BIFilterApi[]limit: BIQueryLimitApirows: BIFieldApi[]diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 075bddd2bd54..c42176b47e5b 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -8395,6 +8395,9 @@ export interface BIValueApi {export interface BIConfigApi {chartType: ChartDisplayTypeApicolumns: BIFieldApi[]+ /** Column that receives the worksheet and dashboard date range. */+ dateField?: BIFieldApi | null+ dateRange?: DateRangeApi | nullfilters: BIFilterApi[]limit: BIQueryLimitApirows: BIFieldApi[]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4b67648b887e..fd1bc2b76c97 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -10721,6 +10721,9 @@ export namespace Schemas {export interface BIConfig {chartType: ChartDisplayType;columns: BIField[];+ /** Column that receives the worksheet and dashboard date range. */+ dateField?: BIField | null;+ dateRange?: DateRange | null;filters: BIFilter[];limit: BIQueryLimit;rows: BIField[];