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(bi): explore catalog snapshots and propose worksheet metrics (#118000)

Marius Andraf0d00ac7cba4
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index e37a65d38146..0bf2eba933eb 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -338,6 +338,10 @@ BI chart settings preserve custom scatter axes and implicit count formatting. Nu
## Connected fields in BI mode
+Catalog SQL metrics can open as BI query snapshots. Their dates, grouping, and bound values come from the metric definition; shelf edits, worksheet date filters, pivots, and result drilling are unavailable. Changing the chart changes the presentation of those results. Saved snapshots do not follow later catalog edits.
+
+After running a worksheet, **Propose as catalog metric** sends its resolved SQL and date window through catalog review. A pending or failed query cannot be proposed. Proposing an existing metric name updates its definition for review. Direct-connection worksheets cannot be proposed as catalog metrics.
+
Below Dimensions and Measures, **Connections** lists the selected table's linked tables and views.
Expand a connection to load its dimensions, measures, and nested connections. Inside connections,
fields and further links appear without section headings.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2699394b3df7..0861dcb4e996 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6731,21 +6731,21 @@ snapshots:
products-business-intelligence-worksheet-exploration--filters-and-hierarchy--light:
hash: v1.k794b7964.8c2bff687cbc922da82ba749edd32061fe5191582e8baac9ddd20b777f297fb2.EgsY3Ud8wKXl6CuNR2L55vxZb1xMvZuNvR42pxQvV8U
products-business-intelligence-worksheet-exploration--narrow--dark:
- hash: v1.k794b7964.84cc0e5ededef8d70ec2afb262cc42d39b3db123a564f1e0663fcb8149793855.yV6x8wpb8M-X_eOhoABzLqsbreU-JcxiG0uERMmVt_k
+ hash: v1.k794b7964.c2ecc6cea28c5701a2d7d72002317ce67e5f9ffe8548797e824069308c082f2b.J6G38qE1SLlWrkppkrJ7mD7maWZ6pzlBCABkjXCWSEY
products-business-intelligence-worksheet-exploration--narrow--light:
- hash: v1.k794b7964.0fee0f5823ffe92065e82cbb68cf41af052ef0686f4af6983f002e14b6b7cc72.VIRLrujj_vgA_1g5UdicDqQ1qqGE4uomAIV93eW7YIk
+ hash: v1.k794b7964.0d6f93656d101dd8d5600f11cd6643c6f5fabdfad5c006bac1ab702429dd9a66.gd-uhTHz6jIKdVgTOBhUj0WLEOXA_m-SjEU5Zu9aUHo
products-business-intelligence-worksheet-exploration--nested-panes--dark:
- hash: v1.k794b7964.3e76ca0186b6784cb53bc5667226aa6dfaaf4d92a6f982e3365910b9f7f31091.xAwVWiSYxRTE9e54QvJX7gNVkNwsqra7QiE0kIbq0Q8
+ hash: v1.k794b7964.218b7fd4d24667390e1666c115f21c90e9b3957129c528bf6760e2e39c194992.gUYAGBuFquGN4LgdYwStgjDQuUYZ2qxLWY_08EI2Iuk
products-business-intelligence-worksheet-exploration--nested-panes--light:
- hash: v1.k794b7964.8c6dcf9cadf2215cee04327bf88673f21f9c2ee5a9526e3f07fa8f4a0bb667db.-2mZYEXSjzrs0vrb1jtq75LeXqI_NMroZz2FLy4m2Pg
+ hash: v1.k794b7964.2ebc6150777a12d9c398410bfaf2820108e122e6c07407af2d126a83d2ddc439.PKf3bczXtp35m1DXPQ4so_boXl93aNUz0DooE4lzFsQ
products-business-intelligence-worksheet-exploration--nested-panes-narrow--dark:
- hash: v1.k794b7964.b61fdbeb9cc286a97b9be1285be1ba26bc8d5ae54257eb5ba6f9977fc6b8d4d2.xsYA7aflnnawZzi6Pyz-gWZmuC0lzsHMRdaj4Boy0aQ
+ hash: v1.k794b7964.ed61aa59e082662cb1914a6e72ebae13475c86808b58955fa1f69695f90bee95.Pn7HURm4BPFeBrfSNXCFA3LDLbnkcPXrh2AIRIyx100
products-business-intelligence-worksheet-exploration--nested-panes-narrow--light:
- hash: v1.k794b7964.8a8174cd2f8d94932b79cfcbfb3061bb67c7109254ddadd458f91429fec79881.S7wrY4iKVI9PT8lh5oMU_DS-m-BjJNZf1_3-vJPS5no
+ hash: v1.k794b7964.c2ab12c4528d86d9932c6fd9713ef82d030e9dc0f946f903dd7396880d0e7cea.4QqDEMssL-yVsRYmtHdPGFlionrXtG4Ju9O7jT7ewgc
products-business-intelligence-worksheet-exploration--scatter-selection--dark:
- hash: v1.k794b7964.16b94e8d73a8d564096dc3c3600cccf22d4d1d123605ad499d6a3e0ccd8dfe11.Q5QHE8jnCZ_xX7p1RXGnV3BafVmnqUoYxwBoWBxyqyg
+ hash: v1.k794b7964.773c169e93e46e3dafdc884a47e048fbc2fed63f795120710ec8cea09de09ab8.DazQyK-hWdi19M-HAMBeSk3ChlLEKI0PjQjKVt9qMk8
products-business-intelligence-worksheet-exploration--scatter-selection--light:
- hash: v1.k794b7964.f862962672535e38e8687d2eeb6cf279719f0594be616d90027904eee06b4714.LJ3rLIyxwpuSgEMQNPieT_dZ4QX4cMWQ0dKXmivZH_I
+ hash: v1.k794b7964.04c507a97cd1974daa89666b36095e130261a28bad09caa9eef143bcc709028a.tKuO2pdvEX1RAxk59DMG9ah_C4sFSFNhm80BYlokjso
products-business-intelligence-worksheet-exploration--sql-preview--dark:
hash: v1.k794b7964.0c799dde5f45d0132adea9cd565d4ef7d074b78255da1138a1b9c76b5030373c.1fmdtlQ1z0XQlGBswx8rJNK2wmfkwWYd-WdqLJaAMyg
products-business-intelligence-worksheet-exploration--sql-preview--light:
@@ -10055,37 +10055,37 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
hash: v1.k794b7964.69c71d482b1b19aa18a81b5ba0fc0bb038d8f3bdc9bdb0a7286c9addb4893dc2.LjgKhmcTELX-Cd50ZnnKmKLTGxv3AH0cD5BfLrBKfQ8
scenes-app-data-warehouse-sql-editor--bi-category-groups--dark:
- hash: v1.k794b7964.c158c80d19a121e48585e800db84ae2125bbb8fbc9bcf0deeddfd263feec998f.JLqXfTgqdGwdzrKjQgf9jSiw9ukb40D2-YALSpZNRi0
+ hash: v1.k794b7964.5486cfd4fbec00ef6dfce4af0c0b6227fccb585e51428af1152c2b301a116f8e.pb_byOmoFqC1G6b5HCLTGbohiMMLZYjIq_CG4CNDGBI
scenes-app-data-warehouse-sql-editor--bi-category-groups--light:
- hash: v1.k794b7964.9366d76f8b1edb1df9b9c82505f006fbf65fc270868e195836b71b3270fc5d78.Vo8WtoaxQ07wF2bqAmTQMEMojU5Y2FHlwYAMA_mlw9A
+ hash: v1.k794b7964.77089560df14ae7eea62b6e946584cbde100897607a5024da7afb7b610eb9178.lPvbJOhNK9XWXXIj10hftrcenyJr0zwRVWf7FtQlb2Y
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
hash: v1.k794b7964.039dfc5ac1a3224b1358554580f5345b074438a646e3b5605bf8e7ad8c9e7948.AjLIYjRJTdHfTNb3UhE0g4-5IBkbo23rsnbptb7S8-0
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
hash: v1.k794b7964.582748cd75a7ea4d5422219d44a7565803c569d2b4e271672057a313b416d012.nDtqgPf06i4bncbB6Uvdp8w0LzJs2_jVJu5qR3c6g5M
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.caaa6e84fffcf675878f0a09bad6134ebaa6cfb50cc070c33bb3dff8b958e74a.kVdrknVYYYAU9YHXvyBR_fJY9ECIRMrQjSyQ4wPud2s
+ hash: v1.k794b7964.40b945046a6e236c5c01c078e82631437277569944eb821fccae1edf9474ed26.kwLpD-OQo0u_WfYl7SiDuIMh-6wfQXA-BaZau9oGtX4
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.875ef03d5e6c52a24f1acee4d533f21f82dad540ab826321c9691e39318b0b07.58UiwOHnzdr3D6hzN9NiL_KBJEB9xt9EYYIhaH2p324
+ hash: v1.k794b7964.3e2ea89c46eb704cf469456601f1775d8da1a49c4ead8faf671f254d33791772.psHiqZUEdESJbBR01RXbczrWCVQttnCagOGiGWIgiME
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.92b754e850177df5cc7d2b07fc9f5008d21d29563113a3f327e16eddac47af7c.C6bQoXo3G3rCtd8Pm8qd6W-sVralk-7onTQlATl4BTQ
+ hash: v1.k794b7964.f400b545df5a6c219abd5cdb85e7c419ba9a31352088d2790e8e259e45ada6c6.wRMD5oyHdIuAcce53FVT7EkWSP0boyafPHIhZen5A9A
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.4eeb5871a96119890608f584c6f82d59c159b69ffcf2cfb83b809d489882c989.L5Rh7rK7C-esP9pNXkAT41lvr4RO-N2R2mY7wEfRjJk
+ hash: v1.k794b7964.1fb81956b9085ac122bf31468978b467d1d1b0de28c1cd4cf6e7813453b68eef.9CXg4SN3f79zu6CyrAgjQtGHk-f0nmB-wdc1fdvPprA
scenes-app-data-warehouse-sql-editor--bi-drilldown--dark:
hash: v1.k794b7964.68ae5a2217951bbe57ab020a5c2f480c527652f64cd0e7c1569d2f6c3c89e5a2.G7_jPjpNVTuk4_6CVl67UZo6EekgmkQXTrlzz5FYo0Y
scenes-app-data-warehouse-sql-editor--bi-drilldown--light:
hash: v1.k794b7964.51e20f9ed3a5f71042d79308c84e8e8f69e16e9fb08fa0ffffd9d07962d7f7c3.-vKccSWyHN6kWTyUG2uog8aNS0DRBIm8oOxOpcxX-7E
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.f36b0bf584fbbceb8bd969587fbbff7b423ae4e460313014bf2ac20f85946849.hLUzhJxWrWp5aTQt39Imx1_EXEgQVlLaClPf6iPIteE
+ hash: v1.k794b7964.2117538c4b7e9e266f7b456acedc8c64216a93297a1b82467b0c203f6e1aafb3.8kUP50nopTeHMRQqWxTln7SHcYDvw8cr5iyuR-NOHcc
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.79cface1c7e2e6b5dd657a14f6d4a997cc98143d538aa377b580db832f3fdeef._aEyz2kOYYqtgaJeasZE9TTBb3cfGAIcb0wm9shlSfo
+ hash: v1.k794b7964.158e1f21f396bd7871a8f891dba3e4089ead9b7f74b7a37569a3d2adf5545fe3.PjAX5DqE6hNBtEBT56hhR82awngZoE8c0bB2M4LQKI8
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
hash: v1.k794b7964.9cdaf1b941fa6fac0d8839b4165ddd0506ce1c1ac263ae447087461a77e85a93.gXKbXKNUGG_zCLxpBvyfnmrOVGKBJj4sYQLELwogzNE
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
hash: v1.k794b7964.99ecf94f32c88b943651332b786c3ab33d4497730016ec325f279c53683bfd59.UE1Sw435eYovzC5VHT6kQceuUqT8J1rNMicQQlbSOL0
scenes-app-data-warehouse-sql-editor--bi-measure-display--dark:
- hash: v1.k794b7964.f529e2c5638d74fb5bff567fab52f54bbba11defb2c5ab4cb0c45e21d9652480.CJgpLpP8LvLhP6m2xrkg736avQ6KmDSKMiBuhKAButk
+ hash: v1.k794b7964.51f59642bed45cd9dfbe798bbd3536eaa54b55924fae7a5256c77d3b273605fa.ltiQQviBGOzy-QRdFr2uOImGmmE9Vb1G8i2rrWeGEnQ
scenes-app-data-warehouse-sql-editor--bi-measure-display--light:
- hash: v1.k794b7964.f96bde99c5c5d5df8c0ba96f196280a6fd1c8133ed8da3390fef550c6e72ed08.1BADjmjMYuB84m4r2uri2k0PduKXPXeF3w0PWLSw90k
+ hash: v1.k794b7964.ff215a24b23e97f27faa7af7a77191cc2211fffebfdc98da6d03706cb5617c3b.IGxOinR-UZLLXlTwHaS6a5pP1LHIjPe80P5KSHsrUmU
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
hash: v1.k794b7964.6309ca3f3ecb88032969e856079e14cda460aa306a5172863693ff8a95ea011c.dIXWRHfmipDgezW97RK0MYne72aosXhe0o1S_uXrt_w
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
@@ -10095,9 +10095,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-named-hierarchy--light:
hash: v1.k794b7964.9874234c76d2c58ad97cdf71da93b03f6fedb482c0978185e6ad1602aeb42249.nzTwYRAxxTDrANQu-17ktAwKi1IAx8R8YEWiDAU1usY
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--dark:
- hash: v1.k794b7964.cabae245ff0e0d2def8041d8f927d377a0d3b058b175cc6a89660d2011b55e74.8pC3w5r2NMav84LvZJoMtgyhz6p3OawsN7T_kEXJZYw
+ hash: v1.k794b7964.43fb0813c76a3150bc7d9822039c21ac4ea7afe64942aede00adff5fbf7aaca8.MWXIoEhyFjUR6VgfQq2c1CqX_vpWMh3Nlp-HmraJuyU
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--light:
- hash: v1.k794b7964.49f47426f598920577bcc65465da4a7f871346b90a1b8a9f1e6ea191be004624.uhKgL-k0RtQFg4FlBhduXL-O1HVVSepEVuNboEHvg_A
+ hash: v1.k794b7964.098fa2b52e946c8a8a00e7d6e57ae8e09106be1096b84c40df246fe2591e4ab9.BjUZmUH58fdYZ02zTNpjrWu5Egzs6qO7iKiIUihZerk
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
hash: v1.k794b7964.c6b39669db3163a1446f19e827a1a19ecaba0147d6315d0c86acb7f34f120e20.mxLctVjcrANyDO_D-QE5mtOAIzwOx8ZYIQvvV_TP0hs
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
@@ -10107,13 +10107,13 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--light:
hash: v1.k794b7964.eb1aea6031e30bcfe43e27164ff819824d11629618fd663fa5bdde8cc9017633.jfPZq39IiqS7_BWpn_l-jnBTj9YRv3CxcGk9T8fwC9M
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.4d13b12b769c301fcfc7723fdef2a3e85d530d66ebf8afa42d525ba3c02f662a.DOojzPyaTHL69a5ISTCSU6JNoy7KD97_UXbNoS9mtRM
+ hash: v1.k794b7964.7f1945f31b95452ed99b30ebb2b2eef7c0caacb36abc054a265ee53449e37f9e.ykm55yd9KG8eAFIxVM93v_K1Diq06RroOnQbnJxfCJQ
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.bab558516256c898c7d9e308a63ef5b589c10cc2f49d6c40cc1ef6fe8481bae8.Q5A72Pk-CB-dqEWlUnVwInDKtPV0Ux9qglovSNAQSh4
+ hash: v1.k794b7964.270586f7fef306862223ea244ef58ba8e4254c870875a713b2fdcea14b2c5e14.IOxSQL1mcIhfKphM1slmtrJd1fpco_nXUCB1jhG1AKo
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.b8c59ff0b3a26d3755c29db048ca81e146b298d141853aaa8aced566f7e6f54a.Q_V-lYTeUHqWrWUJb4N70jjm6KCpdXdpn_tNHZeinhI
+ hash: v1.k794b7964.61c1871d782552c623ed4b53b8cbbf5a74109c58c17a1efec32bf90499d1355f.0ewioRgpY540Ex6B6vk7wbB5mnXcCBoVhdnxIOTZq5o
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.6ab561d7058c6fcb2782b897f6cb8dc2015fa04fcd2ae9ae65409d4eab434b9b.0A1j8TXXyutI1kgB0ejINCo9XXGZwp45J3NoVg1BTtM
+ hash: v1.k794b7964.7988ded7ac073159043f62d9e123c093b1eda90e77bd59209931ca97e10711d7.3jjgY4ose6bTwS4iaT56UJVc9idxnub6wKoIHR9z9MA
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.06df092616d217a4ebdaf0f5f35015c05fe63f5bc1e9b9c39dcdf6594293c0e3.D8zEjaefT5868HRYC8F6GkfsuMMlcxSxekM5z-VoXyM
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index fbe98f3aa876..efabe9a129dd 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -234,7 +234,8 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
variablesOverride: props.variablesOverride,
}
const { inspect } = useActions(biDrilldownLogic(drilldownProps))
- const canDrill = query.kind === NodeKind.BIVisualizationNode && !props.inSharedMode
+ const isQuerySnapshot = query.kind === NodeKind.BIVisualizationNode && !!query.config.querySnapshot
+ const canDrill = query.kind === NodeKind.BIVisualizationNode && !isQuerySnapshot && !props.inSharedMode
const { seriesBreakdownData } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
const { goalLines } = useValues(displayLogic)
@@ -436,6 +437,10 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
The returned columns do not match this worksheet. Run the query again or check the selected fields.
</LemonBanner>
)
+ } else if (isQuerySnapshot && effectiveVisualizationType === ChartDisplayType.TwoDimensionalHeatmap) {
+ component = (
+ <LemonBanner type="info">Query snapshots do not support pivots. Choose another chart type.</LemonBanner>
+ )
} else if (
query.kind === NodeKind.BIVisualizationNode &&
(query.config.chartType === ChartDisplayType.TwoDimensionalHeatmap ||
@@ -662,6 +667,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
<AddVariableButton buttonProps={{ size: controlSize }} />
{sourceFeatures.has(QueryFeature.dateRangePicker) &&
+ !(query.kind === NodeKind.BIVisualizationNode && query.config.querySnapshot) &&
!router.values.location.pathname.includes(urls.sqlEditor()) && ( // decouple this component from insights tab and datawarehouse scene
<DateRange
key="date-range"
@@ -676,7 +682,14 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
)}
<div className={props.context?.chartTypeSelectorClassName}>
- <TableDisplay size={controlSize} />
+ <TableDisplay
+ size={controlSize}
+ disabledReasonFor={(chartType) =>
+ isQuerySnapshot && chartType === ChartDisplayType.TwoDimensionalHeatmap
+ ? 'Query snapshots do not support pivots'
+ : undefined
+ }
+ />
</div>
<LemonButton
diff --git a/products/business_intelligence/frontend/BIEditor.tsx b/products/business_intelligence/frontend/BIEditor.tsx
index 7a0ecb9044a0..10811e3845d0 100644
--- a/products/business_intelligence/frontend/BIEditor.tsx
+++ b/products/business_intelligence/frontend/BIEditor.tsx
@@ -2,11 +2,12 @@ import { BindLogic, useActions, useValues } from 'kea'
import { useRef, type ReactNode, type Ref } from 'react'
import { IconX } from '@posthog/icons'
-import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonTag } from '@posthog/lemon-ui'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { resizerLogic, ResizerLogicProps } from 'lib/components/Resizer/resizerLogic'
import { IconTableChart } from 'lib/lemon-ui/icons'
+import { urls } from 'scenes/urls'
import { BICalculatedMeasureModal } from 'products/business_intelligence/frontend/BICalculatedMeasureModal'
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
@@ -49,6 +50,62 @@ export function BIEditor({
const { desiredSize } = useValues(resizerLogic(biEditorResizerProps))
const biSidePaneWidth = Math.min(400, Math.max(180, desiredSize ?? 240))
+ const contextPanel = activePanel && (!config.querySnapshot || activePanel === 'display') && (
+ <aside
+ className="absolute inset-y-0 right-0 z-10 flex w-72 max-w-full flex-col border-l bg-surface-primary shadow-md @5xl/bi-editor:static @5xl/bi-editor:max-w-[25%] @5xl/bi-editor:shrink-0 @5xl/bi-editor:shadow-none"
+ aria-label={
+ activePanel === 'charts' ? 'Charts' : activePanel === 'analysis' ? 'Analysis' : 'Chart settings'
+ }
+ data-attr="bi-editor-context-panel"
+ >
+ <div className="flex items-center justify-between border-b px-2 py-1">
+ <span className="text-sm font-semibold">
+ {activePanel === 'charts' ? 'Charts' : activePanel === 'analysis' ? 'Analysis' : 'Chart settings'}
+ </span>
+ <LemonButton
+ icon={<IconX />}
+ size="xsmall"
+ type="tertiary"
+ aria-label="Close panel"
+ onClick={() => setActivePanel(null)}
+ data-attr="bi-editor-close-panel"
+ />
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto" ref={settingsPanelRef}>
+ {activePanel === 'charts' && (
+ <>
+ <BIChartTypes />
+ <BIMarksCard />
+ </>
+ )}
+ {activePanel === 'analysis' && <BIAnalysisControls />}
+ </div>
+ </aside>
+ )
+
+ if (config.querySnapshot) {
+ return (
+ <BindLogic logic={biEditorLogic} props={{ tabId }}>
+ <div className="@container/bi-editor flex min-h-0 flex-1 flex-col" data-attr="bi-catalog-snapshot">
+ <LemonBanner type="info">
+ Query snapshot: dates and dimensions are fixed by the metric definition. Changing the chart does
+ not regroup the data. This copy does not track later catalog edits.
+ {config.catalogMetric && (
+ <LemonButton size="xsmall" to={urls.dataCatalogMetric(config.catalogMetric)}>
+ View catalog definition
+ </LemonButton>
+ )}
+ </LemonBanner>
+ <BIToolbar />
+ <div className="relative flex min-h-0 flex-1">
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">{children}</div>
+ {contextPanel}
+ </div>
+ </div>
+ </BindLogic>
+ )
+ }
+
return (
<BindLogic logic={biEditorLogic} props={{ tabId }}>
<div
@@ -156,46 +213,7 @@ export function BIEditor({
<BIFiltersCard />
<div className="flex min-h-0 flex-1 flex-col">{children}</div>
</div>
- {activePanel && (
- <aside
- className="absolute inset-y-0 right-0 z-10 flex w-72 max-w-full flex-col border-l bg-surface-primary shadow-md @5xl/bi-editor:static @5xl/bi-editor:max-w-[25%] @5xl/bi-editor:shrink-0 @5xl/bi-editor:shadow-none"
- aria-label={
- activePanel === 'charts'
- ? 'Charts'
- : activePanel === 'analysis'
- ? 'Analysis'
- : 'Chart settings'
- }
- data-attr="bi-editor-context-panel"
- >
- <div className="flex items-center justify-between border-b px-2 py-1">
- <span className="text-sm font-semibold">
- {activePanel === 'charts'
- ? 'Charts'
- : activePanel === 'analysis'
- ? 'Analysis'
- : 'Chart settings'}
- </span>
- <LemonButton
- icon={<IconX />}
- size="xsmall"
- type="tertiary"
- aria-label="Close panel"
- onClick={() => setActivePanel(null)}
- data-attr="bi-editor-close-panel"
- />
- </div>
- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto" ref={settingsPanelRef}>
- {activePanel === 'charts' && (
- <>
- <BIChartTypes />
- <BIMarksCard />
- </>
- )}
- {activePanel === 'analysis' && <BIAnalysisControls />}
- </div>
- </aside>
- )}
+ {contextPanel}
</div>
</div>
</BindLogic>
diff --git a/products/business_intelligence/frontend/BIMetricProposalButton.tsx b/products/business_intelligence/frontend/BIMetricProposalButton.tsx
new file mode 100644
index 000000000000..c26abefa5b2c
--- /dev/null
+++ b/products/business_intelligence/frontend/BIMetricProposalButton.tsx
@@ -0,0 +1,39 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+
+import { getBIMetricSnapshot } from './biCatalog'
+import { biMetricProposalLogic } from './biMetricProposalLogic'
+import { getBIVisualizationSource } from './biQueryResults'
+import { biSceneLogic } from './biSceneLogic'
+
+export function BIMetricProposalButton({ tabId }: { tabId: string }): JSX.Element {
+ const { worksheet, name, lastRunQuery, dataNodeKey } = useValues(biSceneLogic({ tabId }))
+ const { response, responseLoading, responseError } = useValues(
+ dataNodeLogic({
+ key: dataNodeKey,
+ query: getBIVisualizationSource(lastRunQuery ?? worksheet),
+ autoLoad: !!lastRunQuery,
+ })
+ )
+ const snapshot = getBIMetricSnapshot(worksheet, lastRunQuery, response, !responseLoading && !responseError)
+ const { proposeMetric } = useActions(biMetricProposalLogic({ tabId, config: worksheet.config, snapshot, name }))
+ return (
+ <LemonButton
+ size="small"
+ onClick={proposeMetric}
+ disabledReason={
+ worksheet.source.connectionId
+ ? 'Catalog metrics currently support project and warehouse data'
+ : !snapshot
+ ? 'Run the current worksheet successfully before proposing its query'
+ : undefined
+ }
+ data-attr="bi-propose-metric"
+ >
+ Propose as catalog metric
+ </LemonButton>
+ )
+}
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
index 216354b6a766..eab4db9508d5 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
@@ -23,6 +23,7 @@ import { BIEditor } from './BIEditor'
import { biEditorLogic } from './biEditorLogic'
import { BIEditorView } from './biEditorTypes'
import { getBIHierarchyParent } from './biHierarchies'
+import { BIMetricProposalButton } from './BIMetricProposalButton'
import { BIResultSummary } from './BIResultSummary'
import { keepBIScatterRows } from './biScatter'
import { biSceneLogic } from './biSceneLogic'
@@ -178,6 +179,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
data-attr="bi-worksheet-actions"
/>
</LemonMenu>
+ <BIMetricProposalButton tabId={tabId} />
<LemonButton
type="primary"
size="small"
@@ -241,7 +243,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
context={{
insightProps: { dashboardItemId: `new-bi-${tabId}` },
showOpenEditorButton: false,
- chartTypeSelectorClassName: 'hidden',
+ chartTypeSelectorClassName: worksheet.config.querySnapshot ? undefined : 'hidden',
onEditBIAxis: setEditingAxis,
onDrillBIHierarchy: (next) => navigateHierarchy(next),
biHierarchyDrillDisabledReason: displayedQueryIsCurrent
@@ -266,13 +268,15 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
) : (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-4 text-secondary">
<span>
- {worksheet.config.source
- ? worksheet.config.rows.length ||
- worksheet.config.columns.length ||
- worksheet.config.values.length
- ? 'Press Run to see the results of this worksheet.'
- : 'Drag or double-click a field to start. Dimensions define groups; measures calculate a value for each group.'
- : 'Select a table and add fields to build your worksheet.'}
+ {worksheet.config.querySnapshot
+ ? 'Press Run to see the results of this query snapshot.'
+ : worksheet.config.source
+ ? worksheet.config.rows.length ||
+ worksheet.config.columns.length ||
+ worksheet.config.values.length
+ ? 'Press Run to see the results of this worksheet.'
+ : 'Drag or double-click a field to start. Dimensions define groups; measures calculate a value for each group.'
+ : 'Select a table and add fields to build your worksheet.'}
</span>
{worksheet.config.source &&
!worksheet.config.rows.length &&
@@ -293,7 +297,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
)}
</div>
)}
- <BIResultSummary tabId={tabId} />
+ {!worksheet.config.querySnapshot && <BIResultSummary tabId={tabId} />}
</BIEditor>
)}
{editingAxis && (
diff --git a/products/business_intelligence/frontend/biCatalog.test.ts b/products/business_intelligence/frontend/biCatalog.test.ts
new file mode 100644
index 000000000000..e39f29f75961
--- /dev/null
+++ b/products/business_intelligence/frontend/biCatalog.test.ts
@@ -0,0 +1,63 @@
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { catalogMetricWorksheet, getBIMetricSnapshot } from './biCatalog'
+import { BIEditorView, buildBIQuery, DEFAULT_BI_CONFIG, parseBIEditorState } from './biEditorTypes'
+
+it('keeps catalog SQL and bound values unchanged when a worksheet is saved or its chart changes', () => {
+ const source = {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT count(*) FROM events WHERE timestamp >= {start}',
+ values: { start: '2026-01-01' },
+ }
+ const node = catalogMetricWorksheet({ name: 'revenue', definition: source })!
+ const parsed = parseBIEditorState(BIEditorView.BI, JSON.stringify(node.config))!.config
+ expect(buildBIQuery({ ...parsed, chartType: ChartDisplayType.BoldNumber })?.node.source).toEqual(source)
+ expect(parsed.catalogMetric).toBe('revenue')
+ expect(
+ parseBIEditorState(
+ BIEditorView.BI,
+ JSON.stringify({ ...DEFAULT_BI_CONFIG, querySnapshot: null, catalogMetric: null })
+ )
+ ).not.toBeNull()
+ expect(
+ catalogMetricWorksheet({ name: 'unsupported', definition: { kind: 'MarkdownDefinition', markdown: 'Steps' } })
+ ).toBeNull()
+})
+
+it('only proposes the successfully executed current query, retaining resolved dates and its row cap', () => {
+ const node = catalogMetricWorksheet({
+ name: 'revenue',
+ definition: { kind: NodeKind.HogQLQuery, query: 'SELECT 42' },
+ })!
+ const response = { hogql: "SELECT 42 WHERE toDate('2026-01-01') < toDate('2026-01-08') LIMIT 1001" }
+ expect(getBIMetricSnapshot(node, node, response, true)).toBe(`SELECT * FROM (${response.hogql}) LIMIT 1000`)
+ expect(getBIMetricSnapshot(node, node, response, false)).toBeNull()
+ expect(
+ getBIMetricSnapshot({ ...node, source: { ...node.source, query: 'SELECT 43' } }, node, response, true)
+ ).toBeNull()
+})
+
+it.each([' ', '\n '])('removes a comparison probe by group from resolved HogQL with whitespace %p', (space) => {
+ const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ compareFilter: { compare: true },
+ limit: 100,
+ }
+ const node = { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode as const, config }
+ const hogql = [
+ 'WITH bi_comparison_ranked AS (SELECT 1 AS bi_comparison_rank)',
+ 'SELECT * FROM',
+ 'bi_comparison_ranked WHERE',
+ 'lessOrEquals(bi_comparison_rank, 51) ORDER BY',
+ 'bi_comparison_rank ASC,',
+ 'bi_comparison ASC LIMIT 102',
+ ].join(space)
+ const snapshot = getBIMetricSnapshot(node, node, { hogql }, true)
+ expect(snapshot).toContain('lessOrEquals(bi_comparison_rank, 50)')
+ expect(snapshot).toMatch(/LIMIT 100$/)
+ expect(snapshot).toMatch(/^WITH bi_comparison_ranked/)
+ expect(getBIMetricSnapshot(node, node, { hogql: 'SELECT 1' }, true)).toBeNull()
+})
diff --git a/products/business_intelligence/frontend/biCatalog.ts b/products/business_intelligence/frontend/biCatalog.ts
new file mode 100644
index 000000000000..b227d934c3ec
--- /dev/null
+++ b/products/business_intelligence/frontend/biCatalog.ts
@@ -0,0 +1,63 @@
+import { deepEqual } from 'fast-equals'
+
+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { DataCatalogMetricApi } from 'products/data_catalog/frontend/generated/api.schemas'
+
+import { getBIComparisonGroupLimit } from './biComparisonLimit'
+import { DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+export function catalogMetricWorksheet(
+ metric: Pick<DataCatalogMetricApi, 'name' | 'definition'>
+): BIVisualizationNode | null {
+ const definition = metric.definition
+ if (definition?.kind !== NodeKind.HogQLQuery || typeof definition.query !== 'string') {
+ return null
+ }
+ const source: HogQLQuery = {
+ kind: NodeKind.HogQLQuery,
+ query: definition.query,
+ ...(definition.values ? { values: definition.values as HogQLQuery['values'] } : {}),
+ }
+ return {
+ kind: NodeKind.BIVisualizationNode,
+ source,
+ display: ChartDisplayType.ActionsTable,
+ config: {
+ ...DEFAULT_BI_CONFIG,
+ chartType: ChartDisplayType.ActionsTable,
+ querySnapshot: source,
+ catalogMetric: metric.name,
+ },
+ }
+}
+
+export function getBIMetricSnapshot(
+ worksheet: BIVisualizationNode,
+ lastRun: BIVisualizationNode | null,
+ response: unknown,
+ ready: boolean
+): string | null {
+ if (
+ !ready ||
+ !deepEqual(worksheet.source, lastRun?.source) ||
+ !response ||
+ typeof response !== 'object' ||
+ !('hogql' in response) ||
+ typeof response.hogql !== 'string'
+ ) {
+ return null
+ }
+ if (worksheet.config.compareFilter?.compare && !worksheet.config.querySnapshot) {
+ // Only rewrite our generated outer clause: a row LIMIT can split a comparison group.
+ const probeClause =
+ /(FROM\s+bi_comparison_ranked\s+WHERE\s+lessOrEquals\(bi_comparison_rank,\s*)\d+(\)\s+ORDER BY\s+bi_comparison_rank ASC,\s+bi_comparison ASC\s+LIMIT\s+)\d+\s*$/
+ const limit = getBIComparisonGroupLimit(worksheet.config)
+ return probeClause.test(response.hogql)
+ ? response.hogql.replace(probeClause, (_match, prefix, suffix) => `${prefix}${limit}${suffix}${limit * 2}`)
+ : null
+ }
+ return `SELECT * FROM (${response.hogql}) LIMIT ${worksheet.config.limit}`
+}
diff --git a/products/business_intelligence/frontend/biEditorAnalytics.ts b/products/business_intelligence/frontend/biEditorAnalytics.ts
index cb14f49ee111..d313614e95c9 100644
--- a/products/business_intelligence/frontend/biEditorAnalytics.ts
+++ b/products/business_intelligence/frontend/biEditorAnalytics.ts
@@ -35,6 +35,7 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
config.filters.filter((filter) => filter.operator === 'custom').length
return {
+ catalog_snapshot: !!config.querySnapshot,
local_group_count: config.localFields?.filter((field) => field.localDefinition?.kind === 'groups').length ?? 0,
local_bin_count: config.localFields?.filter((field) => field.localDefinition?.kind === 'bins').length ?? 0,
result_filter_count: config.resultFilters?.length ?? 0,
@@ -86,6 +87,10 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
}
export type BIWorksheetAction =
+ | 'catalog_metric_opened'
+ | 'catalog_metric_proposed'
+ | 'catalog_source_opened'
+ | 'catalog_relationship_requested'
| 'starter_selected'
| 'filter_values_searched'
| 'filter_values_page_loaded'
@@ -117,7 +122,8 @@ export function captureBIWorksheetAction(
hierarchy_axis?: 'rows' | 'columns'
hierarchy_depth?: number
expanded?: boolean
- starter_kind?: 'events'
+ starter_kind?: 'metric' | 'certified_source' | 'events'
+ source_certification?: 'certified' | 'deprecated' | 'unmarked'
} = {}
): void {
posthog.capture(BI_EDITOR_EVENTS.WORKSHEET_ACTION, {
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 89328c4f0a27..b0a0e9aab673 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -98,6 +98,8 @@ function setDataSourceInConfig(config: BIConfig, source: BIDataSource): BIConfig
localFields: undefined,
hierarchies: undefined,
colorBy: undefined,
+ querySnapshot: undefined,
+ catalogMetric: undefined,
comparisonPeriod: undefined,
rows: [],
columns: [],
@@ -1325,7 +1327,9 @@ export const biEditorLogic = kea<biEditorLogicType>([
generatedQuery: [
(selectors) => [selectors.config],
(config: BIConfig): BIQueryBuildResult | null =>
- config.rows.length || config.columns.length || config.values.length ? buildBIQuery(config) : null,
+ config.querySnapshot || config.rows.length || config.columns.length || config.values.length
+ ? buildBIQuery(config)
+ : null,
],
sortOptions: [
(selectors) => [selectors.config],
@@ -1540,7 +1544,11 @@ export const biEditorLogic = kea<biEditorLogicType>([
upsertHierarchy: () => actions.runAfterChange(),
removeHierarchy: () => actions.runAfterChange(),
setDataSource: () => {
- captureBIWorksheetAction('source_selected', values.config)
+ captureBIWorksheetAction('source_selected', values.config, {
+ source_certification:
+ values.allTables.find((table) => table.name === values.config.source?.table)?.certification
+ ?.status ?? 'unmarked',
+ })
actions.runAfterChange()
},
setValueAggregation: () => actions.runAfterChange(),
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 7391feca578f..9ab711575d94 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -693,6 +693,14 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
if (candidate.comparisonPeriod != null && candidate.comparisonPeriod !== 'previous') {
return null
}
+ if (
+ (candidate.querySnapshot != null &&
+ (candidate.querySnapshot.kind !== NodeKind.HogQLQuery ||
+ typeof candidate.querySnapshot.query !== 'string')) ||
+ (candidate.catalogMetric != null && typeof candidate.catalogMetric !== 'string')
+ ) {
+ return null
+ }
if (!isBIAnalysisConfig(candidate)) {
return null
}
@@ -839,6 +847,8 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
}
: {}),
...(candidate.colorBy === null || typeof candidate.colorBy === 'string' ? { colorBy: candidate.colorBy } : {}),
+ ...(candidate.querySnapshot ? { querySnapshot: candidate.querySnapshot } : {}),
+ ...(candidate.catalogMetric ? { catalogMetric: candidate.catalogMetric } : {}),
...(candidate.localFields ? { localFields: candidate.localFields } : {}),
...(candidate.hierarchies ? { hierarchies: candidate.hierarchies } : {}),
...(candidate.memberAliases ? { memberAliases: candidate.memberAliases } : {}),
@@ -1494,6 +1504,12 @@ function buildOrderByExpression(
}
export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQueryBuildResult | null {
+ if (config.querySnapshot) {
+ return {
+ query: config.querySnapshot.query,
+ node: { kind: NodeKind.DataVisualizationNode, source: config.querySnapshot, display: config.chartType },
+ }
+ }
config = normalizeBIConfig(config)
if (
!config.source ||
diff --git a/products/business_intelligence/frontend/biMetricProposalLogic.test.ts b/products/business_intelligence/frontend/biMetricProposalLogic.test.ts
new file mode 100644
index 000000000000..293c78d94205
--- /dev/null
+++ b/products/business_intelligence/frontend/biMetricProposalLogic.test.ts
@@ -0,0 +1,91 @@
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { biMetricProposalLogic } from './biMetricProposalLogic'
+
+afterEach(() => jest.restoreAllMocks())
+
+it('shows a failed proposal and allows retrying the same form', async () => {
+ initKeaTests()
+ let attempts = 0
+ useMocks({
+ post: {
+ '/api/projects/:team_id/data_catalog/metrics/': async ({ request }) => {
+ attempts++
+ return attempts === 1
+ ? [400, { detail: 'Definition could not be saved.' }]
+ : [
+ 201,
+ {
+ ...((await request.json()) as Record<string, unknown>),
+ id: 'retry-metric',
+ status: 'proposed',
+ },
+ ]
+ },
+ },
+ })
+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '')
+ const open = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => undefined)
+ const logic = biMetricProposalLogic({
+ tabId: 'proposal-retry',
+ name: 'Purchases',
+ config: DEFAULT_BI_CONFIG,
+ snapshot: 'SELECT 7',
+ })
+ const unmount = logic.mount()
+ try {
+ logic.actions.proposeMetric()
+ const form = open.mock.calls[0][0]
+ const fields = { ...form.initialValues, name: 'purchases', description: 'Completed purchases.' }
+ await expect(form.onSubmit(fields)).rejects.toBeDefined()
+ expect(toast).toHaveBeenCalledWith('Definition could not be saved.')
+ await expect(form.onSubmit(fields)).resolves.toBeUndefined()
+ expect(attempts).toBe(2)
+ } finally {
+ unmount()
+ }
+})
+
+it('validates an initializing form and submits one fixed snapshot while a request is pending', async () => {
+ initKeaTests()
+ let releaseRequest!: () => void
+ const pending = new Promise<void>((resolve) => {
+ releaseRequest = resolve
+ })
+ const create = jest.fn(async ({ request }: { request: Request }) => {
+ const body = await request.json()
+ await pending
+ return [201, { ...body, id: 'metric-example', status: 'proposed' }]
+ })
+ useMocks({ post: { '/api/projects/:team_id/data_catalog/metrics/': create } })
+ const open = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => undefined)
+ const logic = biMetricProposalLogic({
+ tabId: 'proposal-test',
+ name: 'Weekly purchases',
+ config: DEFAULT_BI_CONFIG,
+ snapshot: 'SELECT 42 LIMIT 1000',
+ })
+ logic.mount()
+ logic.actions.proposeMetric()
+ const form = open.mock.calls[0][0]
+ expect(form.errors?.name(undefined, {})).toBeTruthy()
+ expect(form.errors?.description(undefined, {})).toBeTruthy()
+ const fields = { ...form.initialValues, name: 'weekly_purchases', description: 'Purchases in this date window.' }
+ const submissions = Promise.all([form.onSubmit(fields), form.onSubmit(fields)])
+ releaseRequest()
+ await submissions
+ expect(create).toHaveBeenCalledTimes(1)
+ const result = await create.mock.results[0].value
+ expect(result[1]).toMatchObject({
+ name: 'weekly_purchases',
+ display_name: 'Weekly purchases',
+ definition: { kind: 'HogQLQuery', query: 'SELECT 42 LIMIT 1000' },
+ })
+ logic.unmount()
+})
diff --git a/products/business_intelligence/frontend/biMetricProposalLogic.tsx b/products/business_intelligence/frontend/biMetricProposalLogic.tsx
new file mode 100644
index 000000000000..a5fdd368f6df
--- /dev/null
+++ b/products/business_intelligence/frontend/biMetricProposalLogic.tsx
@@ -0,0 +1,129 @@
+import { MakeLogicType, actions, kea, key, listeners, path, props } from 'kea'
+
+import { LemonDialog, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'
+
+import { ApiError } from 'lib/api'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import { METRIC_FIELD_COPY, validateMetricDescription, validateMetricName } from 'products/data_catalog/frontend/common'
+import { dataCatalogMetricsCreate } from 'products/data_catalog/frontend/generated/api'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
+
+import { captureBIEditorQuerySaved, captureBIWorksheetAction } from './biEditorAnalytics'
+import { BIEditorView } from './biEditorTypes'
+
+interface BIMetricProposalProps {
+ tabId: string
+ config: BIConfig
+ snapshot: string | null
+ name: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biMetricProposalLogicActions {
+ proposeMetric: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biMetricProposalLogicMeta {
+ key: string
+}
+
+export type biMetricProposalLogicType = MakeLogicType<
+ {},
+ biMetricProposalLogicActions,
+ BIMetricProposalProps,
+ biMetricProposalLogicMeta
+>
+
+export const biMetricProposalLogic = kea<biMetricProposalLogicType>([
+ props({} as BIMetricProposalProps),
+ key((props) => props.tabId),
+ path((key) => ['products', 'business_intelligence', 'biMetricProposalLogic', key]),
+ actions({ proposeMetric: true }),
+ listeners(({ props }) => ({
+ proposeMetric: () => {
+ if (!props.snapshot || props.config.source?.connectionId) {
+ return
+ }
+ const snapshot = props.snapshot
+ const config = props.config
+ let submission: Promise<void> | null = null
+ LemonDialog.openForm({
+ title: 'Propose as catalog metric',
+ description:
+ 'Saves this query with the date window and filters from its last run. Shelves and worksheet history are not part of the metric. An existing metric name updates that definition. Changes go through catalog review.',
+ shouldAwaitSubmit: true,
+ primaryButtonProps: { children: 'Propose metric' },
+ initialValues: { name: '', display_name: props.name, description: '', unit: '' },
+ content: (
+ <>
+ <LemonField name="name" label={METRIC_FIELD_COPY.name.label}>
+ <LemonInput placeholder={METRIC_FIELD_COPY.name.placeholder} autoFocus />
+ </LemonField>
+ <LemonField name="display_name" label={METRIC_FIELD_COPY.displayName.label}>
+ <LemonInput placeholder={METRIC_FIELD_COPY.displayName.placeholder} />
+ </LemonField>
+ <LemonField name="description" label={METRIC_FIELD_COPY.description.label}>
+ <LemonTextArea
+ placeholder={METRIC_FIELD_COPY.description.placeholder}
+ minRows={2}
+ stopPropagation
+ />
+ </LemonField>
+ <LemonField name="unit" label={METRIC_FIELD_COPY.unit.label}>
+ <LemonInput placeholder={METRIC_FIELD_COPY.unit.placeholder} />
+ </LemonField>
+ </>
+ ),
+ errors: {
+ name: (value) => validateMetricName((value ?? '').trim()),
+ description: (value) =>
+ !value?.trim() ? 'Add a description' : validateMetricDescription(value.trim()),
+ },
+ onSubmit: async (fields) => {
+ if (submission) {
+ return submission
+ }
+ submission = (async () => {
+ const metric = await dataCatalogMetricsCreate(String(teamLogic.values.currentTeamId), {
+ name: fields.name.trim(),
+ display_name: (fields.display_name ?? '').trim(),
+ description: fields.description.trim(),
+ unit: (fields.unit ?? '').trim(),
+ definition: { kind: NodeKind.HogQLQuery, query: snapshot },
+ })
+ metricsLogic.findMounted()?.actions.loadMetrics()
+ captureBIEditorQuerySaved({ editorView: BIEditorView.BI, config }, 'metric', 'create')
+ captureBIWorksheetAction('catalog_metric_proposed', config)
+ lemonToast.success(
+ <>
+ Metric proposed. <Link to={urls.dataCatalogMetric(metric.name)}>Review in catalog</Link>
+ </>
+ )
+ })()
+ .catch((error) => {
+ lemonToast.error(
+ error instanceof ApiError && error.detail
+ ? error.detail
+ : 'Could not propose the metric. Try again.'
+ )
+ throw error
+ })
+ .finally(() => {
+ submission = null
+ })
+ return submission
+ },
+ })
+ },
+ })),
+])
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index 7bcba0195440..1457b8ed7d0b 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -124,6 +124,42 @@ describe('biSceneLogic', () => {
})
afterEach(() => logic.unmount())
+ it('opens catalog definitions as fixed snapshots and waits for Run', async () => {
+ const runQuery = jest.fn(() => [200, { columns: ['revenue'], results: [[42]] }])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/revenue/': {
+ name: 'revenue',
+ display_name: 'Revenue',
+ definition: { kind: NodeKind.HogQLQuery, query: 'SELECT 42 AS revenue' },
+ },
+ },
+ post: { '/api/environments/:team_id/query/HogQLQuery/': runQuery },
+ })
+ await expectLogic(logic, () =>
+ router.actions.push(urls.businessIntelligenceNew(), { metric: 'revenue' })
+ ).toFinishAllListeners()
+ expect(logic.values.name).toBe('Revenue')
+ expect(logic.values.worksheet.config.querySnapshot?.query).toBe('SELECT 42 AS revenue')
+ expect(logic.values.lastRunQuery).toBeNull()
+ expect(logic.values.worksheet.config.source).toBeNull()
+ const dataLogic = dataNodeLogic({
+ key: logic.values.dataNodeKey,
+ query: logic.values.worksheet.source,
+ autoLoad: false,
+ })
+ const unmount = dataLogic.mount()
+ try {
+ expect(runQuery).not.toHaveBeenCalled()
+ await expectLogic(logic, () => logic.actions.runQuery()).toFinishAllListeners()
+ expect(logic.values.lastRunQuery?.source.query).toBe('SELECT 42 AS revenue')
+ expect(runQuery).toHaveBeenCalledTimes(1)
+ expect(dataLogic.values.response).toMatchObject({ results: [[42]] })
+ } finally {
+ unmount()
+ }
+ })
+
it.each([false, true])('protects unsaved worksheet edits when navigating away (saved: %s)', async (saved) => {
const confirm = jest.spyOn(window, 'confirm').mockReturnValue(false)
try {
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index 65fbfda6b05c..bc9527dbc980 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -32,6 +32,8 @@ import { ChartSettings, HogQLFilters, NodeKind, VisualizationNode } from '~/quer
import { isBIVisualizationNode } from '~/queries/utils'
import { AccessControlLevel, AccessControlResourceType, ChartDisplayType } from '~/types'
+import { validateMetricName } from 'products/data_catalog/frontend/common'
+import { dataCatalogMetricsRetrieve } from 'products/data_catalog/frontend/generated/api'
import { warehouseSavedQueriesCreate } from 'products/data_warehouse/frontend/generated/api'
import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'
import { connectionSelectorLogic } from 'products/data_warehouse/frontend/shared/logics/connectionSelectorLogic'
@@ -46,6 +48,7 @@ import { BIVisualizationNodeApi, InsightApi } from 'products/product_analytics/f
import type { BIConfig } from '../../../frontend/src/queries/schema/schema-business-intelligence'
import type { DataWarehouseSavedQueryApi } from '../../data_warehouse/frontend/generated/api.schemas'
import type { ExternalDataSourceConnectionOptionApi } from '../../warehouse_sources/frontend/generated/api.schemas'
+import { catalogMetricWorksheet } from './biCatalog'
import { captureBIEditorQueryRun, captureBIEditorQuerySaved, captureBIWorksheetAction } from './biEditorAnalytics'
import { biEditorLogic } from './biEditorLogic'
import {
@@ -176,6 +179,9 @@ export interface biSceneLogicActions {
navigateHierarchy: (worksheet: BIVisualizationNode) => {
worksheet: BIVisualizationNode
}
+ openCatalogMetric: (name: string) => {
+ name: string
+ }
openWorksheet: () => {
value: true
}
@@ -344,6 +350,7 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
shareWorksheet: true,
syncWorksheetUrl: true,
openWorksheet: true,
+ openCatalogMetric: (name: string) => ({ name }),
clearInsight: true,
selectConnection: (connectionId: string | null) => ({ connectionId }),
setExportViewName: (name: string) => ({ name }),
@@ -598,6 +605,34 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
actions.setSqlPreviewVersion(values.generatedQuery ? 'current' : 'last_run')
}
},
+ openCatalogMetric: async ({ name }, breakpoint) => {
+ try {
+ if (validateMetricName(name)) {
+ throw new Error('Invalid metric name')
+ }
+ const metric = await dataCatalogMetricsRetrieve(String(values.currentTeamId), name)
+ breakpoint()
+ if (router.values.searchParams.metric !== name || router.values.hashParams.q) {
+ return
+ }
+ const worksheet = catalogMetricWorksheet(metric)
+ if (!worksheet) {
+ throw new Error(
+ 'Explore in BI currently supports SQL metrics. Open this definition in the catalog.'
+ )
+ }
+ actions.clearInsight()
+ actions.restoreWorksheet(worksheet)
+ actions.setLastRunQuery(null)
+ actions.setName(metric.display_name || metric.name)
+ actions.recordWorksheet(true)
+ actions.syncWorksheetUrl()
+ captureBIWorksheetAction('catalog_metric_opened', worksheet.config)
+ } catch (error) {
+ breakpoint()
+ lemonToast.error(error instanceof Error ? error.message : 'Could not load the catalog metric')
+ }
+ },
recordWorksheet: ({ reset }) => {
if (!cache.restoringHistory) {
actions.pushHistory(
@@ -793,12 +828,16 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
return
}
captureBIEditorQueryRun({ editorView: BIEditorView.BI, config: values.config })
+ const dataLogic = dataNodeLogic.findMounted({ key: values.dataNodeKey })
const unchanged =
!!values.lastRunQuery &&
equal(getBIVisualizationSource(values.lastRunQuery), getBIVisualizationSource(values.worksheet))
+ const waitingForFirstRun =
+ dataLogic?.props.autoLoad === false &&
+ equal(dataLogic.props.query, getBIVisualizationSource(values.worksheet))
actions.setLastRunQuery(values.worksheet)
- if (unchanged) {
- dataNodeLogic.findMounted({ key: values.dataNodeKey })?.actions.loadData('force_async')
+ if (unchanged || waitingForFirstRun) {
+ dataLogic?.actions.loadData('force_async')
}
},
cancelQuery: () => dataNodeLogic.findMounted({ key: values.dataNodeKey })?.actions.cancelQuery(),
@@ -905,6 +944,10 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
},
openWorksheet: () => {
const { searchParams, hashParams } = router.values
+ if (typeof searchParams.metric === 'string' && !hashParams.q) {
+ actions.openCatalogMetric(searchParams.metric)
+ return
+ }
const pathId = router.values.location.pathname.match(/\/bi\/([^/]+)$/)?.[1]
const insightShortId =
searchParams.open_insight || (pathId && pathId !== 'new' ? decodeURIComponent(pathId) : undefined)
diff --git a/products/business_intelligence/frontend/components/BIToolbar.tsx b/products/business_intelligence/frontend/components/BIToolbar.tsx
index 34640c285c60..ee017670e234 100644
--- a/products/business_intelligence/frontend/components/BIToolbar.tsx
+++ b/products/business_intelligence/frontend/components/BIToolbar.tsx
@@ -47,7 +47,7 @@ export function BIToolbar(): JSX.Element {
type="primary"
onClick={responseLoading ? cancelQuery : runQuery}
disabledReason={
- !config.source
+ !config.source && !config.querySnapshot
? 'Select a table before running'
: !generatedQuery
? config.rows.length || config.columns.length || config.values.length
@@ -68,121 +68,130 @@ export function BIToolbar(): JSX.Element {
data-attr="bi-editor-auto-update"
/>
<LemonDivider vertical />
- <LemonButton
- icon={<IconSwapHoriz />}
- size="xsmall"
- type="tertiary"
- tooltip="Swap rows and columns"
- aria-label="Swap rows and columns"
- disabledReason={
- config.rows.length === 0 && config.columns.length === 0 && config.values.length === 0
- ? 'No fields to swap'
- : undefined
- }
- onClick={swapRowsAndColumns}
- data-attr="bi-editor-swap"
- />
- <LemonButton
- icon={<IconArrowUp />}
- size="xsmall"
- type="tertiary"
- active={config.sort?.direction === 'asc'}
- tooltip="Sort ascending"
- aria-label="Sort ascending"
- disabledReason={noSortReason}
- onClick={() => quickSort('asc')}
- data-attr="bi-editor-sort-ascending"
- />
- <LemonButton
- icon={<IconArrowDown />}
- size="xsmall"
- type="tertiary"
- active={config.sort?.direction === 'desc'}
- tooltip="Sort descending"
- aria-label="Sort descending"
- disabledReason={noSortReason}
- onClick={() => quickSort('desc')}
- data-attr="bi-editor-sort-descending"
- />
- <LemonSelect
- value={config.sort?.key ?? null}
- options={[
- {
- value: null,
- label: 'Auto',
- tooltip: 'Sorts dates from oldest to newest, or other dimensions by the highest value first.',
- },
- ...sortOptions.map((option) => ({ value: option.key, label: option.label })),
- ]}
- onChange={(key) => setSort(key === null ? null : { key, direction: config.sort?.direction ?? 'desc' })}
- renderButtonContent={(option) => `Sort: ${option?.label ?? 'Auto'}`}
- icon={<IconSort />}
- aria-label="Sort results by"
- size="xsmall"
- type="tertiary"
- dropdownMatchSelectWidth={false}
- disabledReason={sortOptions.length === 0 ? 'Add a field to rows or columns first' : undefined}
- data-attr="bi-editor-sort"
- />
- <LemonSelect
- value={config.limit}
- options={LIMIT_OPTIONS}
- onChange={setLimit}
- renderButtonContent={(option) => `Aggregated rows: ${option?.label ?? config.limit}`}
- aria-label="Aggregated result row limit"
- tooltip="Maximum aggregated result rows, after grouping and calculations. This does not limit the source rows read."
- size="xsmall"
- type="tertiary"
- dropdownMatchSelectWidth={false}
- data-attr="bi-editor-query-limit"
- />
- <LemonDivider vertical />
- <BIDateControls />
- {config.comparisonPeriod && (
- <span className="text-xs text-secondary">Comparison window of this reference range</span>
+ {!config.querySnapshot && (
+ <>
+ <LemonButton
+ icon={<IconSwapHoriz />}
+ size="xsmall"
+ type="tertiary"
+ tooltip="Swap rows and columns"
+ aria-label="Swap rows and columns"
+ disabledReason={
+ config.rows.length === 0 && config.columns.length === 0 && config.values.length === 0
+ ? 'No fields to swap'
+ : undefined
+ }
+ onClick={swapRowsAndColumns}
+ data-attr="bi-editor-swap"
+ />
+ <LemonButton
+ icon={<IconArrowUp />}
+ size="xsmall"
+ type="tertiary"
+ active={config.sort?.direction === 'asc'}
+ tooltip="Sort ascending"
+ aria-label="Sort ascending"
+ disabledReason={noSortReason}
+ onClick={() => quickSort('asc')}
+ data-attr="bi-editor-sort-ascending"
+ />
+ <LemonButton
+ icon={<IconArrowDown />}
+ size="xsmall"
+ type="tertiary"
+ active={config.sort?.direction === 'desc'}
+ tooltip="Sort descending"
+ aria-label="Sort descending"
+ disabledReason={noSortReason}
+ onClick={() => quickSort('desc')}
+ data-attr="bi-editor-sort-descending"
+ />
+ <LemonSelect
+ value={config.sort?.key ?? null}
+ options={[
+ {
+ value: null,
+ label: 'Auto',
+ tooltip:
+ 'Sorts dates from oldest to newest, or other dimensions by the highest value first.',
+ },
+ ...sortOptions.map((option) => ({ value: option.key, label: option.label })),
+ ]}
+ onChange={(key) =>
+ setSort(key === null ? null : { key, direction: config.sort?.direction ?? 'desc' })
+ }
+ renderButtonContent={(option) => `Sort: ${option?.label ?? 'Auto'}`}
+ icon={<IconSort />}
+ aria-label="Sort results by"
+ size="xsmall"
+ type="tertiary"
+ dropdownMatchSelectWidth={false}
+ disabledReason={sortOptions.length === 0 ? 'Add a field to rows or columns first' : undefined}
+ data-attr="bi-editor-sort"
+ />
+ <LemonSelect
+ value={config.limit}
+ options={LIMIT_OPTIONS}
+ onChange={setLimit}
+ renderButtonContent={(option) => `Aggregated rows: ${option?.label ?? config.limit}`}
+ aria-label="Aggregated result row limit"
+ tooltip="Maximum aggregated result rows, after grouping and calculations. This does not limit the source rows read."
+ size="xsmall"
+ type="tertiary"
+ dropdownMatchSelectWidth={false}
+ data-attr="bi-editor-query-limit"
+ />
+ <LemonDivider vertical />
+ <BIDateControls />
+ {config.comparisonPeriod && (
+ <span className="text-xs text-secondary">Comparison window of this reference range</span>
+ )}
+ <LemonDivider vertical />
+ </>
)}
- <LemonDivider vertical />
<LemonButton
size="xsmall"
type="tertiary"
onClick={resetConfig}
- disabledReason={!config.source ? 'Nothing to clear' : undefined}
+ disabledReason={!config.source && !config.querySnapshot ? 'Nothing to clear' : undefined}
data-attr="bi-editor-clear"
>
Clear sheet
</LemonButton>
- <div className="ml-auto flex flex-wrap items-center gap-1">
- <LemonButton
- size="xsmall"
- type="secondary"
- active={fieldsPaneOpen}
- onClick={toggleFieldsPane}
- aria-pressed={fieldsPaneOpen}
- data-attr="bi-editor-toggle-fields"
- >
- Fields
- </LemonButton>
- <LemonButton
- size="xsmall"
- type="secondary"
- active={activePanel === 'charts'}
- onClick={() => setActivePanel(activePanel === 'charts' ? null : 'charts')}
- aria-expanded={activePanel === 'charts'}
- data-attr="bi-editor-show-me"
- >
- Charts
- </LemonButton>
- <LemonButton
- size="xsmall"
- type="secondary"
- active={activePanel === 'analysis'}
- onClick={() => setActivePanel(activePanel === 'analysis' ? null : 'analysis')}
- aria-expanded={activePanel === 'analysis'}
- data-attr="bi-editor-analysis"
- >
- Analysis
- </LemonButton>
- </div>
+ {!config.querySnapshot && (
+ <div className="ml-auto flex flex-wrap items-center gap-1">
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ active={fieldsPaneOpen}
+ onClick={toggleFieldsPane}
+ aria-pressed={fieldsPaneOpen}
+ data-attr="bi-editor-toggle-fields"
+ >
+ Fields
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ active={activePanel === 'charts'}
+ onClick={() => setActivePanel(activePanel === 'charts' ? null : 'charts')}
+ aria-expanded={activePanel === 'charts'}
+ data-attr="bi-editor-show-me"
+ >
+ Charts
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ active={activePanel === 'analysis'}
+ onClick={() => setActivePanel(activePanel === 'analysis' ? null : 'analysis')}
+ aria-expanded={activePanel === 'analysis'}
+ data-attr="bi-editor-analysis"
+ >
+ Analysis
+ </LemonButton>
+ </div>
+ )}
</div>
)
}
diff --git a/products/data_catalog/frontend/DataCatalogMetricScene.tsx b/products/data_catalog/frontend/DataCatalogMetricScene.tsx
index f3a785621bb9..c0888bf8dbbb 100644
--- a/products/data_catalog/frontend/DataCatalogMetricScene.tsx
+++ b/products/data_catalog/frontend/DataCatalogMetricScene.tsx
@@ -200,6 +200,16 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProp
}
const actions: MetricAction[] = [
+ ...(featureFlags[FEATURE_FLAGS.SQL_EDITOR_BI_MODE] && definitionSql
+ ? [
+ {
+ key: 'explore-bi',
+ label: 'Explore in BI',
+ icon: <IconGraph />,
+ onClick: () => router.actions.push(urls.businessIntelligenceNew(), { metric: metric.name }),
+ },
+ ]
+ : []),
...(isApproved
? []
: [