Skip to content

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

fix(insights): skip the override warning when a sql insight ignores it (#114456)

Thomas Obermüller0b811eddb2d0
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 5f19a60d6bc9..dc948780a0ed 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -559,7 +559,11 @@ export function InsightMeta({
: urls.insightEdit(short_id, dashboardId)
)}
fullWidth
- {...getOverrideWarningPropsForButton(filtersOverride, variablesOverride)}
+ {...getOverrideWarningPropsForButton(
+ insight.query,
+ filtersOverride,
+ variablesOverride
+ )}
>
Edit
</LemonButton>
diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
index 1cc91044c4da..283d5b96bfe0 100644
--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
@@ -25,6 +25,8 @@ describe('sql-utils', () => {
['plain placeholder', 'SELECT * FROM events WHERE {filters}', true],
['field placeholder', 'SELECT * FROM events WHERE {filters.properties}', true],
['column-bound placeholder', 'SELECT * FROM v WHERE {filters(day AS timestamp)}', true],
+ ['placeholder with inner whitespace', 'SELECT * FROM events WHERE { filters }', true],
+ ['field placeholder with inner whitespace', 'SELECT * FROM events WHERE {\n filters.properties\n}', true],
['line-commented placeholder', 'SELECT * FROM events\n-- {filters}', false],
['inline line-commented placeholder', 'SELECT * FROM events -- WHERE {filters}', false],
['block-commented placeholder', 'SELECT * FROM events /* WHERE {filters} */', false],
diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
index 52e4830532e3..b35c64a7e526 100644
--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
@@ -3,6 +3,7 @@ import { analyzeTablesAndColumns } from './hogqlParserWorkerManager'
export { normalizeIdentifier } from './hogqlAst'
const FILTERS_BOUND_PREFIX = '{filters('
+const FILTERS_PLACEHOLDER_REGEX = /\{\s*filters\s*[}.(]/y
// Returns the index after the string literal or comment starting at `i`, or null when neither starts there.
const skipNonCode = (query: string, i: number): number | null => {
@@ -50,8 +51,17 @@ const skipNonCode = (query: string, i: number): number | null => {
return null
}
+const tokenStartsAt = (query: string, token: string | RegExp, i: number): boolean => {
+ if (typeof token === 'string') {
+ return query.startsWith(token, i)
+ }
+ token.lastIndex = i
+ return token.test(query)
+}
+
// Whether any of `tokens` appears in the query outside string literals and comments.
-const queryContainsInCode = (query: string | null, tokens: string[]): boolean => {
+// A RegExp token must be sticky, so that it matches only at the current position.
+const queryContainsInCode = (query: string | null, tokens: (string | RegExp)[]): boolean => {
if (!query) {
return false
}
@@ -64,7 +74,7 @@ const queryContainsInCode = (query: string | null, tokens: string[]): boolean =>
continue
}
- if (tokens.some((token) => query.startsWith(token, i))) {
+ if (tokens.some((token) => tokenStartsAt(query, token, i))) {
return true
}
@@ -75,7 +85,7 @@ const queryContainsInCode = (query: string | null, tokens: string[]): boolean =>
}
export const queryUsesFiltersPlaceholder = (query: string | null): boolean =>
- queryContainsInCode(query, ['{filters}', '{filters.', FILTERS_BOUND_PREFIX])
+ queryContainsInCode(query, [FILTERS_PLACEHOLDER_REGEX])
export const queryUsesPlaceholder = (query: string | null, name: string): boolean =>
queryContainsInCode(query, [`{${name}}`])
diff --git a/frontend/src/scenes/insights/InsightPageHeader.tsx b/frontend/src/scenes/insights/InsightPageHeader.tsx
index dec15baabd1f..23d041dd2f18 100644
--- a/frontend/src/scenes/insights/InsightPageHeader.tsx
+++ b/frontend/src/scenes/insights/InsightPageHeader.tsx
@@ -224,7 +224,7 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In
setInsightMode(ItemMode.Edit, null)
}
}}
- {...getOverrideWarningPropsForButton(filtersOverride, variablesOverride)}
+ {...getOverrideWarningPropsForButton(query, filtersOverride, variablesOverride)}
{...(isBIVisualizationNode(query) && !biEnabled
? {
disabledReason:
diff --git a/frontend/src/scenes/insights/utils.overrideWarning.test.ts b/frontend/src/scenes/insights/utils.overrideWarning.test.ts
new file mode 100644
index 000000000000..d217f33e313d
--- /dev/null
+++ b/frontend/src/scenes/insights/utils.overrideWarning.test.ts
@@ -0,0 +1,53 @@
+import { getOverrideWarningPropsForButton } from 'scenes/insights/utils'
+
+import { DataVisualizationNode, HogQLVariable, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
+
+describe('getOverrideWarningPropsForButton()', () => {
+ const sqlInsight = (query: string, variables?: Record<string, HogQLVariable>): DataVisualizationNode => ({
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query, variables },
+ })
+ const trendsInsight: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [{ kind: NodeKind.EventsNode, event: '$pageview' }] },
+ }
+ const endpointVariable: HogQLVariable = { variableId: 'var-1', code_name: 'endpoint', value: 'a' }
+ const dateFilter = { date_from: '-24h' }
+ const endpointOverride = { 'var-1': { ...endpointVariable, value: 'b' } }
+
+ it.each([
+ [
+ 'SQL without a filters placeholder ignores dashboard filters',
+ sqlInsight('SELECT 1'),
+ dateFilter,
+ null,
+ undefined,
+ ],
+ [
+ 'SQL with a filters placeholder uses dashboard filters',
+ sqlInsight('SELECT 1 WHERE {filters}'),
+ dateFilter,
+ null,
+ 'filters',
+ ],
+ [
+ 'SQL uses a dashboard variable it declares',
+ sqlInsight('SELECT {variables.endpoint}', { 'var-1': endpointVariable }),
+ null,
+ endpointOverride,
+ 'variables',
+ ],
+ [
+ 'SQL ignores a dashboard variable it does not declare',
+ sqlInsight('SELECT 1'),
+ null,
+ endpointOverride,
+ undefined,
+ ],
+ ['a regular insight uses dashboard filters', trendsInsight, dateFilter, null, 'filters'],
+ ])('%s', (_name, query, filtersOverride, variablesOverride, expectedOverrideType) => {
+ expect(getOverrideWarningPropsForButton(query, filtersOverride, variablesOverride).tooltip).toEqual(
+ expectedOverrideType ? expect.stringContaining(`dashboard ${expectedOverrideType}`) : undefined
+ )
+ })
+})
diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsx
index 58c91b938148..30f91f9eec1a 100644
--- a/frontend/src/scenes/insights/utils.tsx
+++ b/frontend/src/scenes/insights/utils.tsx
@@ -13,6 +13,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import { objectsEqual } from 'lib/utils/objects'
import { removeUndefinedAndNull } from 'lib/utils/objects'
import { ensureStringIsNotBlank } from 'lib/utils/strings'
+import { queryUsesFiltersPlaceholder } from 'scenes/data-warehouse/editor/sql-utils'
import { isWarehouseSeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -47,7 +48,9 @@ import {
isDataTableNode,
isEventsNode,
isGroupNode,
+ isHogQLQuery,
isInsightVizNode,
+ isNodeWithSource,
} from '~/queries/utils'
import { cleanInsightQuery } from '~/scenes/insights/utils/queryUtils'
import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'
@@ -904,13 +907,27 @@ export function getInsightIconTypeFromQuery(query: any): FileSystemIconType {
}
export const getOverrideWarningPropsForButton = (
+ query: Node | null | undefined,
filtersOverride: DashboardFilter | null | undefined,
variablesOverride: Record<string, HogQLVariable> | null | undefined
): Pick<LemonButtonProps, 'icon' | 'tooltip'> => {
+ // The backend applies dashboard filters to a SQL query only through a {filters} placeholder, and
+ // dashboard variables only to the variables the query declares. Other overrides do not change
+ // the result, so editing discards nothing.
+ const hogQLSource = isHogQLQuery(query)
+ ? query
+ : isNodeWithSource(query) && isHogQLQuery(query.source)
+ ? query.source
+ : null
const filterOverridesExist =
isObject(filtersOverride) &&
- Object.values(filtersOverride).some((value) => value !== null && (!Array.isArray(value) || value.length > 0))
- const variableOverridesExist = isObject(variablesOverride) && !isEmptyObject(variablesOverride)
+ Object.values(filtersOverride).some((value) => value !== null && (!Array.isArray(value) || value.length > 0)) &&
+ (!hogQLSource || queryUsesFiltersPlaceholder(hogQLSource.query))
+ const variableOverridesExist =
+ isObject(variablesOverride) &&
+ (hogQLSource
+ ? Object.keys(variablesOverride).some((variableId) => !!hogQLSource.variables?.[variableId])
+ : !isEmptyObject(variablesOverride))
const overrideType =
filterOverridesExist && variableOverridesExist ? 'overrides' : filterOverridesExist ? 'filters' : 'variables'