Skip to content

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

feat(sql-editor): list hogql metrics in the sidebar (#105220)

Thiago Salvatore0b006e5506f3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e2de724fa424..23cf6288510a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8841,9 +8841,9 @@ snapshots:
scenes-app-experiments--experiment-with-mean-metric--light:
hash: v1.k794b7964.9ba48b1d5d4eb60ec2d989b60a699ee08b5cc8a5e0d110d36b35407bdf516b84.yMae1cArL4zfST4xJ9vHBqbKdLmHNjbGEWMU5d1NjLk
scenes-app-experiments--experiment-with-multi-step-funnel-metric--dark:
- hash: v1.k794b7964.7081860293911912c22c286b58eaa76d20eb830d1cf748991aaad5f03edd179e.NUTXAFVo1yavYY-AS38g6hhObKN3bru1C1YS2K6kw3Y
+ hash: v1.k794b7964.13b0ec97746a8028d4c79bb00f635c8f1f3dca5d155b33a3aa52ee659691a91d.Jwn4dZcGdSGfalsoHrbR1ETRY951nKbR-5daJDjoBG4
scenes-app-experiments--experiment-with-multi-step-funnel-metric--light:
- hash: v1.k794b7964.af14f7a5b3dfaf6798b66f81b80bb8ce6feb4e1052f198e93b2049956b2b0ab4.FvGIr17gWYEfiUdDTzI1vdffBD9QoChjzNbJukXbmZI
+ hash: v1.k794b7964.44f1babf5f70eff3bcb61ce780c57ae14b60e310473f08bb2b71027480dec204.YdEtbcaxUx3wskURC5M-oLR5wijFTpXRqRbXTvQ0AyQ
scenes-app-experiments--experiment-with-multiple-metrics--dark:
hash: v1.k794b7964.abaf9111cbf345951d9d7e9e68574d57df522c42fff4991f1dc30993e5c253f6.D8J9SH5TXG4g5JuFg8yW7BIjN8WqqOkS-efa9T4GsBk
scenes-app-experiments--experiment-with-multiple-metrics--light:
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 5504411541c6..206cdc863f16 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -103,6 +103,7 @@ export const defaultMocks: Mocks = {
'/api/projects/:team_id/actions/': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/annotations/': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/event_definitions/': EMPTY_PAGINATED_RESPONSE,
+ '/api/projects/:team_id/data_catalog/metrics/': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/cohorts/': toPaginatedResponse([MOCK_DEFAULT_COHORT]),
'/api/environments/:team_id/dashboards/': EMPTY_PAGINATED_RESPONSE,
'/api/environments/:team_id/alerts/': EMPTY_PAGINATED_RESPONSE,
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
index 6fa7570eb42b..2a4b55b8fbee 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
@@ -372,6 +372,20 @@ export const QueryDatabase = ({
const getEndpointUrl = (item: TreeDataItem): string => endpointModelUrl(item.record?.table?.name ?? item.name)
+ const getMetricEditorUrl = (item: TreeDataItem): string =>
+ urls.sqlEditor({ source: 'metric', metricName: item.record?.metric.name })
+
+ const openMetricEditor = (item: TreeDataItem, newTab = false): void => {
+ const url = getMetricEditorUrl(item)
+
+ if (newTab || isEmbeddedMode) {
+ newInternalTab(url)
+ return
+ }
+
+ router.actions.push(url)
+ }
+
const treeRef = useRef<LemonTreeRef>(null)
useEffect(() => {
setTreeRef(treeRef)
@@ -447,6 +461,10 @@ export const QueryDatabase = ({
if (item && item.record?.type === 'unsaved-query') {
openUnsavedQuery(item.record)
}
+
+ if (item && item.record?.type === 'metric') {
+ openMetricEditor(item)
+ }
}}
renderItem={(item) => {
// Check if item has search matches for highlighting
@@ -695,6 +713,77 @@ export const QueryDatabase = ({
)
}
+ if (item.record?.type === 'metric') {
+ const metricName = item.record.metric.name
+ const openMetricLabel = 'Open in SQL editor'
+ return (
+ <DropdownMenuGroup>
+ <div className="flex gap-px">
+ {isEmbeddedMode ? (
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ openMetricEditor(item, true)
+ }}
+ >
+ <ButtonPrimitive menuItem>{openMetricLabel}</ButtonPrimitive>
+ </DropdownMenuItem>
+ ) : (
+ <>
+ <DropdownMenuItem asChild>
+ <Link
+ to={getMetricEditorUrl(item)}
+ onClick={(e) => e.stopPropagation()}
+ buttonProps={{
+ menuItem: true,
+ className: 'flex-1 rounded-r-none',
+ }}
+ >
+ {openMetricLabel}
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild>
+ <Link
+ to={getMetricEditorUrl(item)}
+ target="_blank"
+ targetBlankIcon={false}
+ onClick={(e) => e.stopPropagation()}
+ tooltip={openMetricLabel}
+ buttonProps={{
+ menuItem: true,
+ iconOnly: true,
+ className: 'px-2 rounded-l-none',
+ }}
+ >
+ <IconExternal />
+ </Link>
+ </DropdownMenuItem>
+ </>
+ )}
+ </div>
+ <DropdownMenuItem asChild>
+ <Link
+ to={urls.dataCatalogMetric(metricName)}
+ onClick={(e) => e.stopPropagation()}
+ buttonProps={{ menuItem: true }}
+ >
+ View in data catalog
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ void copyToClipboard(metricName)
+ }}
+ >
+ <ButtonPrimitive menuItem>Copy metric name</ButtonPrimitive>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ )
+ }
+
// Show menu for tables
if (item.record?.type === 'table') {
// Per-object access control only exists for actual warehouse tables, not posthog/system tables
@@ -1277,6 +1366,7 @@ export const QueryDatabase = ({
'managed-view',
'endpoint',
'draft',
+ 'metric',
'column',
'unsaved-query',
'folder',
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
index 034ddc089373..766b3a099419 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
@@ -12,6 +12,10 @@ import type { DatabaseSchemaField } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import type { DataWarehouseSavedQuery } from '~/types'
+import { dataCatalogMetricsList } from 'products/data_catalog/frontend/generated/api'
+import type { DataCatalogMetricApi } from 'products/data_catalog/frontend/generated/api.schemas'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
+
import { dataWarehouseViewsLogic } from '../../saved_queries/dataWarehouseViewsLogic'
import { draftsLogic } from '../draftsLogic'
import {
@@ -28,8 +32,29 @@ jest.mock('~/generated/core/api', () => ({
propertyDefinitionsList: jest.fn(),
}))
jest.mock('~/queries/query')
+jest.mock('products/data_catalog/frontend/generated/api', () => ({
+ dataCatalogMetricsList: jest.fn(() => Promise.resolve({ results: [], next: null })),
+}))
const mockPropertyDefinitionsList = propertyDefinitionsList as jest.Mock
+const mockDataCatalogMetricsList = dataCatalogMetricsList as jest.Mock
+
+const buildMetric = (id: string, name: string, definitionKind: string | null): DataCatalogMetricApi => ({
+ id,
+ name,
+ description: '',
+ owner: null,
+ definition_kind: definitionKind,
+ referenced_table_names: [],
+ status: 'approved',
+ is_drifted: false,
+ approved_at: null,
+ approved_by: null,
+ last_run_at: null,
+ created_by: { id: 1, uuid: 'user-uuid', email: '[email protected]', hedgehog_config: null },
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: null,
+})
const jsonField = (name = 'properties'): DatabaseSchemaField => ({
name,
@@ -552,6 +577,78 @@ describe('queryDatabaseLogic', () => {
logic.unmount()
})
+ it('lists only SQL metrics under a metrics section in browsing and search', async () => {
+ initKeaTests()
+ mockDataCatalogMetricsList.mockResolvedValueOnce({
+ results: [
+ buildMetric('m-2', 'weekly_revenue', 'HogQLQuery'),
+ buildMetric('m-1', 'active_users', 'HogQLQuery'),
+ buildMetric('m-3', 'revenue_trend', 'TrendsQuery'),
+ buildMetric('m-4', 'revenue_stub', null),
+ ],
+ next: null,
+ })
+ const logic = queryDatabaseLogic()
+ logic.mount()
+
+ expect(logic.values.treeData.find((item) => item.id === 'metrics')).toBeUndefined()
+ await expectLogic(metricsLogic.findMounted()!).toDispatchActions(['loadMetricsSuccess'])
+
+ const metrics = logic.values.treeData.find((item) => item.id === 'metrics')!
+ expect(metrics.children!.map((item) => [item.id, item.record?.type])).toEqual([
+ ['metric-m-1', 'metric'],
+ ['metric-m-2', 'metric'],
+ ])
+
+ logic.actions.setSearchTerm('revenue')
+ const searchMetrics = logic.values.searchTreeData.find((item) => item.id === 'search-metrics')!
+ expect(searchMetrics.children!.map((item) => item.id)).toEqual(['search-metric-m-2'])
+
+ metricsLogic.findMounted()!.actions.loadMetricsSuccess([buildMetric('m-3', 'revenue_trend', 'TrendsQuery')])
+ expect(logic.values.searchTreeData.find((item) => item.id === 'search-metrics')).toBeUndefined()
+ logic.actions.setSearchTerm('')
+ expect(logic.values.treeData.find((item) => item.id === 'metrics')).toBeUndefined()
+ logic.unmount()
+ })
+
+ it.each([
+ ['a server error', { status: 500 }, ["Couldn't load metrics", 'Try again']],
+ ['a permission denial', { status: 403, code: 'permission_denied' }, null],
+ ])('handles %s when loading metrics', async (_case, error, expectedChildNames) => {
+ initKeaTests()
+ mockDataCatalogMetricsList.mockRejectedValueOnce(error)
+ const logic = queryDatabaseLogic()
+ logic.mount()
+ logic.values.treeData
+ await expectLogic(metricsLogic.findMounted()!).toDispatchActions(['loadMetricsFailure'])
+
+ const metrics = logic.values.treeData.find((item) => item.id === 'metrics')
+ expect(metrics?.children?.map((item) => item.name) ?? null).toEqual(expectedChildNames)
+ logic.unmount()
+ })
+
+ it('loads metrics again from the retry node', async () => {
+ initKeaTests()
+ mockDataCatalogMetricsList
+ .mockRejectedValueOnce({ status: 500 })
+ .mockResolvedValueOnce({ results: [buildMetric('m-1', 'active_users', 'HogQLQuery')], next: null })
+ const logic = queryDatabaseLogic()
+ logic.mount()
+ logic.values.treeData
+ await expectLogic(metricsLogic.findMounted()!).toDispatchActions(['loadMetricsFailure'])
+
+ const retryNode = logic.values.treeData
+ .find((item) => item.id === 'metrics')
+ ?.children?.find((item) => item.name === 'Try again')
+ expect(retryNode?.onClick).toBeTruthy()
+ retryNode?.onClick?.()
+ await expectLogic(metricsLogic.findMounted()!).toDispatchActions(['loadMetricsSuccess'])
+
+ const metrics = logic.values.treeData.find((item) => item.id === 'metrics')!
+ expect(metrics.children!.map((item) => item.id)).toEqual(['metric-m-1'])
+ logic.unmount()
+ })
+
describe('lazy schema hydration', () => {
let logic: ReturnType<typeof queryDatabaseLogic.build>
let dbLogic: ReturnType<typeof databaseTableListLogic.build>
@@ -884,11 +981,12 @@ describe('queryDatabaseLogic', () => {
)
})
- it('hides drafts and unsaved queries when showing a direct connection schema', () => {
+ it('hides drafts, unsaved queries and metrics when showing a direct connection schema', () => {
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EDITOR_DRAFTS], {
[FEATURE_FLAGS.EDITOR_DRAFTS]: true,
})
draftsLogic.actions.setDrafts([{ id: 'draft-id', name: 'test_draft' }] as any)
+ metricsLogic.findMounted()!.actions.loadMetricsSuccess([buildMetric('m-1', 'daily_revenue', 'HogQLQuery')])
logic.actions.loadQueryTabStateSuccess({
id: 'query-tab-state-id',
state: {
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index 1ecf3ec57ac6..4e3fc78feacd 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -9,6 +9,7 @@ import {
IconDocument,
IconEndpoints,
IconFolder,
+ IconGraph,
IconPlug,
IconPlus,
IconRefresh,
@@ -18,6 +19,7 @@ import { LemonMenuItem } from '@posthog/lemon-ui'
import { Spinner } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { isAccessDeniedError } from 'lib/api-error'
import { TreeItem } from 'lib/components/DatabaseTableTree/DatabaseTableTree'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTreeRef, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
@@ -48,6 +50,9 @@ import {
QueryTabState,
} from '~/types'
+import { HOGQL_METRIC_DEFINITION_KIND } from 'products/data_catalog/frontend/common'
+import type { DataCatalogMetricApi } from 'products/data_catalog/frontend/generated/api.schemas'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
import { SourceIcon, mapUrlToProvider } from 'products/data_warehouse/frontend/shared/components/SourceIcon'
import { joinsDataLogic } from 'products/data_warehouse/frontend/shared/logics/joinsDataLogic'
import { viewLinkLogic } from 'products/data_warehouse/frontend/shared/logics/viewLinkLogic'
@@ -266,6 +271,7 @@ export type SearchTreeMatches = {
relevantManagedViews: [DatabaseSchemaManagedViewTable, FuseSearchMatch[] | null][]
relevantDrafts: [DataWarehouseSavedQueryDraft, FuseSearchMatch[] | null][]
relevantEndpointTables: [DatabaseSchemaEndpointTable, FuseSearchMatch[] | null][]
+ relevantMetrics: [DataCatalogMetricApi, FuseSearchMatch[] | null][]
}
export type TreeDataContext = {
@@ -277,6 +283,7 @@ export type TreeDataContext = {
dataWarehouseSavedQueryFolders: DataWarehouseSavedQueryFolder[]
managedViews: DatabaseSchemaManagedViewTable[]
latestEndpointTables: DatabaseSchemaEndpointTable[]
+ hogqlMetrics: DataCatalogMetricApi[]
allTablesMap: Record<string, DatabaseSchemaTable>
}
@@ -694,11 +701,11 @@ const createFieldsErrorNode = (nodeId: string): TreeDataItem => {
}
// A failed schema load must not look like an empty project: say it failed and offer the retry.
-const createSchemaErrorNodes = (prefix: string, onRetry: () => void): TreeDataItem[] => [
+const createLoadErrorNodes = (prefix: string, message: string, onRetry: () => void): TreeDataItem[] => [
{
id: `${prefix}-error/`,
- name: "Couldn't load your schema",
- displayName: <span className="text-danger">Couldn't load your schema</span>,
+ name: message,
+ displayName: <span className="text-danger">{message}</span>,
icon: <IconWarning className="text-danger" />,
disableSelect: true,
type: 'node',
@@ -718,6 +725,9 @@ const createSchemaErrorNodes = (prefix: string, onRetry: () => void): TreeDataIt
},
]
+const createSchemaErrorNodes = (prefix: string, onRetry: () => void): TreeDataItem[] =>
+ createLoadErrorNodes(prefix, "Couldn't load your schema", onRetry)
+
const createDirectConnectionEmptyNodes = (connectionId: string): TreeDataItem[] => [
{
id: 'direct-connection-empty/',
@@ -1304,6 +1314,24 @@ const createDraftNode = (
}
}
+const createMetricNode = (
+ metric: DataCatalogMetricApi,
+ matches: FuseSearchMatch[] | null = null,
+ isSearch = false
+): TreeDataItem => {
+ return {
+ id: `${isSearch ? 'search-' : ''}metric-${metric.id}`,
+ name: metric.name,
+ type: 'node',
+ icon: <IconGraph />,
+ record: {
+ type: 'metric',
+ metric,
+ ...(matches && { searchMatches: matches }),
+ },
+ }
+}
+
const createViewFolderNode = (
folder: DataWarehouseSavedQueryFolder,
children: TreeDataItem[],
@@ -1556,7 +1584,7 @@ const createSourceFolderNode = (
}
const createTopLevelFolderNode = (
- type: 'sources' | 'views' | 'managed-views' | 'drafts',
+ type: 'sources' | 'views' | 'managed-views' | 'drafts' | 'metrics',
children: TreeDataItem[],
isSearch = false,
icon?: JSX.Element
@@ -1612,7 +1640,9 @@ const createTopLevelFolderNode = (
? 'Views'
: type === 'drafts'
? 'Drafts'
- : 'Managed Views',
+ : type === 'metrics'
+ ? 'Metrics'
+ : 'Managed Views',
type: 'node',
icon: icon,
record: {
@@ -1910,6 +1940,7 @@ export interface queryDatabaseLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
joins: DataWarehouseViewLink[] // joinsDataLogic
joinsLoading: boolean // joinsDataLogic
+ allMetrics: DataCatalogMetricApi[] // metricsLogic
currentProjectId: number | string // teamLogic
user: UserType | null // userLogic
activeDraggedViewId: string | null
@@ -1926,7 +1957,9 @@ export interface queryDatabaseLogicValues {
hasNonPosthogSources: boolean
highlightViewsSectionDrop: boolean
highlightedDropFolderId: string | null
+ hogqlMetrics: DataCatalogMetricApi[]
joinsByFieldName: Record<string, DataWarehouseViewLink>
+ metricsLoadFailed: boolean
pendingViewFolderOverrides: Record<string, string | null>
propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>
queryTabState: QueryTabState | null
@@ -1935,6 +1968,7 @@ export interface queryDatabaseLogicValues {
relevantDrafts: [DataWarehouseSavedQueryDraft, FuseSearchMatch[] | null][]
relevantEndpointTables: [DatabaseSchemaEndpointTable, FuseSearchMatch[] | null][]
relevantManagedViews: [DatabaseSchemaManagedViewTable, FuseSearchMatch[] | null][]
+ relevantMetrics: [DataCatalogMetricApi, FuseSearchMatch[] | null][]
relevantPosthogTables: [DatabaseSchemaTable, FuseSearchMatch[] | null][]
relevantSavedQueries: [DataWarehouseSavedQuerySummary, FuseSearchMatch[] | null][]
relevantSavedQueryFolders: [DataWarehouseSavedQueryFolder, FuseSearchMatch[] | null][]
@@ -2009,6 +2043,21 @@ export interface queryDatabaseLogicActions {
deleteJoin: (join: DataWarehouseViewLink) => {
join: DataWarehouseViewLink
} // joinsDataLogic
+ loadMetrics: () => any // metricsLogic
+ loadMetricsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // metricsLogic
+ loadMetricsSuccess: (
+ allMetrics: DataCatalogMetricApi[],
+ payload?: any
+ ) => {
+ allMetrics: DataCatalogMetricApi[]
+ payload?: any
+ } // metricsLogic
toggleEditJoinModal: (join: DataWarehouseViewLink) => {
join: DataWarehouseViewLink
} // viewLinkLogic
@@ -2252,6 +2301,11 @@ export interface queryDatabaseLogicMeta {
latestEndpointTables: DatabaseSchemaEndpointTable[],
searchTerm: string
) => [DatabaseSchemaEndpointTable, FuseSearchMatch[] | null][]
+ hogqlMetrics: (allMetrics: DataCatalogMetricApi[]) => DataCatalogMetricApi[]
+ relevantMetrics: (
+ hogqlMetrics: DataCatalogMetricApi[],
+ searchTerm: string
+ ) => [DataCatalogMetricApi, FuseSearchMatch[] | null][]
selectedDirectSource: (
connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,
connectionId: string | null
@@ -2273,7 +2327,8 @@ export interface queryDatabaseLogicMeta {
relevantSavedQueryFolders: [DataWarehouseSavedQueryFolder, FuseSearchMatch[] | null][],
relevantManagedViews: [DatabaseSchemaManagedViewTable, FuseSearchMatch[] | null][],
relevantDrafts: [DataWarehouseSavedQueryDraft, FuseSearchMatch[] | null][],
- relevantEndpointTables: [DatabaseSchemaEndpointTable, FuseSearchMatch[] | null][]
+ relevantEndpointTables: [DatabaseSchemaEndpointTable, FuseSearchMatch[] | null][],
+ relevantMetrics: [DataCatalogMetricApi, FuseSearchMatch[] | null][]
) => SearchTreeMatches
searchTreeData: (
searchTreeSourceContext: SearchTreeSourceContext,
@@ -2293,6 +2348,7 @@ export interface queryDatabaseLogicMeta {
dataWarehouseSavedQueryFolders: DataWarehouseSavedQueryFolder[],
managedViews: DatabaseSchemaManagedViewTable[],
latestEndpointTables: DatabaseSchemaEndpointTable[],
+ hogqlMetrics: DataCatalogMetricApi[],
allTablesMap: Record<string, DatabaseSchemaTable>
) => TreeDataContext
treeData: (
@@ -2309,7 +2365,8 @@ export interface queryDatabaseLogicMeta {
materializingViewIds: string[],
propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>,
databaseFieldsComplete: boolean,
- tableFieldsStatus: TableFieldsStatus
+ tableFieldsStatus: TableFieldsStatus,
+ metricsLoadFailed: boolean
) => TreeDataItem[]
displayedTreeData: (
searchTerm: string,
@@ -2437,6 +2494,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
'databaseFieldsComplete',
'tableFieldsStatus',
],
+ metricsLogic,
+ ['allMetrics'],
dataWarehouseViewsLogic,
[
'dataWarehouseSavedQueries',
@@ -2472,9 +2531,19 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
['loadDrafts', 'renameDraft', 'loadMoreDrafts'],
databaseTableListLogic,
['refreshDatabaseSchema', 'hydrateTableFields', 'ensureAllTableFields'],
+ metricsLogic,
+ ['loadMetrics', 'loadMetricsSuccess', 'loadMetricsFailure'],
],
})),
reducers({
+ metricsLoadFailed: [
+ false,
+ {
+ loadMetrics: () => false,
+ loadMetricsSuccess: () => false,
+ loadMetricsFailure: (_, { errorObject }) => !isAccessDeniedError(errorObject ?? {}),
+ },
+ ],
editingDraftId: [
null as string | null,
{
@@ -2975,6 +3044,27 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
return latestEndpointTables.map((table) => [table, null])
},
],
+ hogqlMetrics: [
+ (s) => [s.allMetrics],
+ (allMetrics: DataCatalogMetricApi[]): DataCatalogMetricApi[] =>
+ allMetrics
+ .filter((metric) => metric.definition_kind === HOGQL_METRIC_DEFINITION_KIND)
+ .sort((a, b) => a.name.localeCompare(b.name)),
+ ],
+ relevantMetrics: [
+ (s) => [s.hogqlMetrics, s.searchTerm],
+ (
+ hogqlMetrics: DataCatalogMetricApi[],
+ searchTerm: string
+ ): [DataCatalogMetricApi, FuseSearchMatch[] | null][] => {
+ if (searchTerm) {
+ return createFuse<DataCatalogMetricApi>(hogqlMetrics, FUSE_OPTIONS)
+ .search(searchTerm)
+ .map((result) => [result.item, result.matches as FuseSearchMatch[]])
+ }
+ return hogqlMetrics.map((metric) => [metric, null])
+ },
+ ],
selectedDirectSource: [
(s) => [s.connectionOptions, s.connectionId],
(
@@ -3022,6 +3112,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.relevantManagedViews,
s.relevantDrafts,
s.relevantEndpointTables,
+ s.relevantMetrics,
],
(
relevantPosthogTables: [DatabaseSchemaTable, FuseSearchMatch[] | null][],
@@ -3031,7 +3122,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
relevantSavedQueryFolders: [DataWarehouseSavedQueryFolder, FuseSearchMatch[] | null][],
relevantManagedViews: [DatabaseSchemaManagedViewTable, FuseSearchMatch[] | null][],
relevantDrafts: [DataWarehouseSavedQueryDraft, FuseSearchMatch[] | null][],
- relevantEndpointTables: [DatabaseSchemaEndpointTable, FuseSearchMatch[] | null][]
+ relevantEndpointTables: [DatabaseSchemaEndpointTable, FuseSearchMatch[] | null][],
+ relevantMetrics: [DataCatalogMetricApi, FuseSearchMatch[] | null][]
): SearchTreeMatches => ({
relevantPosthogTables,
relevantSystemTables,
@@ -3041,6 +3133,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
relevantManagedViews,
relevantDrafts,
relevantEndpointTables,
+ relevantMetrics,
}),
],
searchTreeData: [
@@ -3084,6 +3177,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
relevantManagedViews,
relevantDrafts,
relevantEndpointTables,
+ relevantMetrics,
} = searchTreeMatches
const tableLookup = createTableLookup({
@@ -3226,6 +3320,14 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
searchResults.push(createTopLevelFolderNode('views', viewsChildren, true))
}
+ const metricsChildren = relevantMetrics.map(([metric, matches]) =>
+ createMetricNode(metric, matches, true)
+ )
+ if (metricsChildren.length > 0) {
+ expandedIds.push('search-metrics')
+ searchResults.push(createTopLevelFolderNode('metrics', metricsChildren, true))
+ }
+
if (managedViewsChildren.length > 0 && !featureFlags[FEATURE_FLAGS.MANAGED_VIEWSETS]) {
expandedIds.push('search-managed-views')
searchResults.push(createTopLevelFolderNode('managed-views', managedViewsChildren, true))
@@ -3265,6 +3367,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.dataWarehouseSavedQueryFolders,
s.managedViews,
s.latestEndpointTables,
+ s.hogqlMetrics,
s.allTablesMap,
],
(
@@ -3276,6 +3379,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
dataWarehouseSavedQueryFolders: DataWarehouseSavedQueryFolder[],
managedViews: DatabaseSchemaManagedViewTable[],
latestEndpointTables: DatabaseSchemaEndpointTable[],
+ hogqlMetrics: DataCatalogMetricApi[],
allTablesMap: Record<string, DatabaseSchemaTable>
): TreeDataContext => ({
allPosthogTables,
@@ -3286,6 +3390,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
dataWarehouseSavedQueryFolders,
managedViews,
latestEndpointTables,
+ hogqlMetrics,
allTablesMap,
}),
],
@@ -3305,6 +3410,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.propertyDefinitionLists,
s.databaseFieldsComplete,
s.tableFieldsStatus,
+ s.metricsLoadFailed,
],
(
treeDataContext: TreeDataContext,
@@ -3320,7 +3426,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
materializingViewIds: string[],
propertyDefinitionLists: Record<string, SidebarPropertyDefinitionList>,
databaseFieldsComplete: boolean,
- tableFieldsStatus: TableFieldsStatus
+ tableFieldsStatus: TableFieldsStatus,
+ metricsLoadFailed: boolean
): TreeDataItem[] => {
const {
allPosthogTables,
@@ -3331,6 +3438,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
dataWarehouseSavedQueryFolders,
managedViews,
latestEndpointTables,
+ hogqlMetrics,
allTablesMap,
} = treeDataContext
const sourcesChildren: TreeDataItem[] = []
@@ -3511,6 +3619,10 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
}
}
+ const metricsChildren = metricsLoadFailed
+ ? createLoadErrorNodes('metrics', "Couldn't load metrics", () => actions.loadMetrics())
+ : hogqlMetrics.map((metric) => createMetricNode(metric))
+
const draftsChildren: TreeDataItem[] = []
if (featureFlags[FEATURE_FLAGS.EDITOR_DRAFTS]) {
@@ -3571,6 +3683,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
]
: []),
createTopLevelFolderNode('views', viewsChildren),
+ ...(metricsChildren.length > 0 ? [createTopLevelFolderNode('metrics', metricsChildren)] : []),
...(featureFlags[FEATURE_FLAGS.MANAGED_VIEWSETS]
? []
: [createTopLevelFolderNode('managed-views', managedViewsChildren)]),
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index f83c4ffac2ad..030caefd45e4 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -29,6 +29,8 @@ import {
import { initKeaTests } from '~/test/init'
import { ChartDisplayType, InsightShortId, InsightModel } from '~/types'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
+
import { BI_EDITOR_EVENTS } from './bi/biEditorAnalytics'
import { biEditorLogic } from './bi/biEditorLogic'
import { BIConfig, BIEditorView, BIField } from './bi/biEditorTypes'
@@ -1211,10 +1213,22 @@ describe('sqlEditorLogic', () => {
})
})
- it('opens an unbound tab when the metric cannot be loaded', async () => {
+ it('opens another metric when the editor already holds a query', async () => {
useMocks({
get: {
- '/api/projects/:team_id/data_catalog/metrics/missing_metric/': [404],
+ '/api/projects/:team_id/data_catalog/metrics/:name/': (req: any) => [
+ 200,
+ {
+ name: req.params.name,
+ definition: {
+ kind: NodeKind.HogQLQuery,
+ query: `SELECT '${req.params.name}'`,
+ ...(req.params.name === 'first_metric' && {
+ filters: { dateRange: { date_from: '-7d' } },
+ }),
+ },
+ },
+ ],
},
})
@@ -1225,9 +1239,89 @@ describe('sqlEditorLogic', () => {
})
logic.mount()
- router.actions.push(urls.sqlEditor(), { source: 'metric', edit_metric: 'missing_metric' })
+ router.actions.push(urls.sqlEditor(), { source: 'metric', edit_metric: 'first_metric' })
+ await expectLogic(logic).toDispatchActions(['createTab', 'setSourceQuery']).toMatchValues({
+ queryInput: "SELECT 'first_metric'",
+ editingMetricName: 'first_metric',
+ })
- await expectLogic(logic).toDispatchActions(['createTab']).toMatchValues({ editingMetricName: null })
+ router.actions.push(urls.sqlEditor(), { source: 'metric', edit_metric: 'second_metric' })
+ await expectLogic(logic)
+ .toDispatchActions(['createTab', 'setSourceQuery'])
+ .toMatchValues({
+ queryInput: "SELECT 'second_metric'",
+ editingMetricName: 'second_metric',
+ sourceQuery: partial({ source: { kind: NodeKind.HogQLQuery, query: "SELECT 'second_metric'" } }),
+ })
+ })
+
+ it.each([
+ ['a metric that cannot be loaded', [404], null],
+ [
+ 'a metric defined by an insight query',
+ [200, { name: 'my_metric', definition: { kind: NodeKind.TrendsQuery, series: [] } }],
+ null,
+ ],
+ ['a stub metric', [200, { name: 'my_metric', definition: null }], 'my_metric'],
+ ])('opens %s in an empty tab', async (_case, response, expectedMetricName) => {
+ useMocks({ get: { '/api/projects/:team_id/data_catalog/metrics/my_metric/': response } })
+
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ logic.actions.setQueryInput('SELECT 1')
+
+ router.actions.push(urls.sqlEditor(), { source: 'metric', edit_metric: 'my_metric' })
+
+ await expectLogic(logic)
+ .toDispatchActions(['createTab', 'setSourceQuery'])
+ .toMatchValues({ editingMetricName: expectedMetricName, queryInput: '' })
+ })
+
+ it('keeps the latest metric when an earlier request answers last', async () => {
+ let releaseSlowMetric: () => void = () => {}
+ const slowMetricReleased = new Promise<void>((resolve) => {
+ releaseSlowMetric = resolve
+ })
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/:name/': async (req: any) => {
+ if (req.params.name === 'slow_metric') {
+ await slowMetricReleased
+ }
+ return [
+ 200,
+ {
+ name: req.params.name,
+ definition: { kind: NodeKind.HogQLQuery, query: `SELECT '${req.params.name}'` },
+ },
+ ]
+ },
+ },
+ })
+
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+
+ router.actions.push(urls.sqlEditor(), { source: 'metric', edit_metric: 'slow_metric' })
+ router.actions.push(urls.sqlEditor(), { source: 'metric', edit_metric: 'fast_metric' })
+ await expectLogic(logic)
+ .toDispatchActions(['createTab', 'setSourceQuery'])
+ .toMatchValues({ editingMetricName: 'fast_metric' })
+
+ releaseSlowMetric()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ queryInput: "SELECT 'fast_metric'",
+ editingMetricName: 'fast_metric',
+ })
})
it('does not request or bind a traversal-shaped edit_metric name', async () => {
@@ -1341,6 +1435,35 @@ describe('sqlEditorLogic', () => {
expect(createBody?.unit).toEqual(expectedOptionalFields.unit)
expect(logic.values.metricPrefill).toBeNull()
})
+
+ it('refreshes the sidebar metric list after saving a metric', async () => {
+ const savedMetrics: Record<string, any>[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/': () => [200, { results: savedMetrics, next: null }],
+ },
+ post: {
+ '/api/projects/:team_id/data_catalog/metrics/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ savedMetrics.push({ name: body.name, definition_kind: NodeKind.HogQLQuery })
+ return [200, { name: body.name }]
+ },
+ },
+ })
+ const catalogMetrics = metricsLogic()
+ catalogMetrics.mount()
+ await expectLogic(catalogMetrics, () => catalogMetrics.actions.loadMetrics()).toDispatchActions([
+ 'loadMetricsSuccess',
+ ])
+ mountEditor()
+ logic.actions.setQueryInput('SELECT count() FROM events')
+
+ logic.actions.saveAsMetricSubmit(PREFILL)
+ await expectLogic(catalogMetrics).toDispatchActions(['loadMetricsSuccess'])
+
+ expect(catalogMetrics.values.allMetrics.map((metric) => metric.name)).toEqual([PREFILL.name])
+ catalogMetrics.unmount()
+ })
})
describe('Update view', () => {
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index a3959f76b3e6..2f1643f5b21d 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -6,6 +6,7 @@ import {
afterMount,
beforeUnmount,
connect,
+ isBreakpoint,
kea,
key,
listeners,
@@ -100,6 +101,7 @@ import {
dataCatalogMetricsPartialUpdate,
dataCatalogMetricsRetrieve,
} from 'products/data_catalog/frontend/generated/api'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
import { validateEndpointName } from 'products/endpoints/frontend/common'
import type { ExternalDataSourceConnectionOptionApi } from '../../../../../products/warehouse_sources/frontend/generated/api.schemas'
@@ -376,6 +378,28 @@ export function normalizeRawQuerySource(source: HogQLQuery): HogQLQuery {
}
}
+function hogQLEditorSourceQuery(source: Partial<HogQLQuery> = {}): DataVisualizationNode {
+ return {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ ...source,
+ kind: NodeKind.HogQLQuery,
+ query: typeof source.query === 'string' ? source.query : '',
+ },
+ display: ChartDisplayType.Auto,
+ }
+}
+
+function metricEditorSourceQuery(definition: Record<string, unknown> | null | undefined): DataVisualizationNode | null {
+ if (!definition) {
+ return hogQLEditorSourceQuery()
+ }
+ if (definition.kind !== NodeKind.HogQLQuery) {
+ return null
+ }
+ return hogQLEditorSourceQuery(definition as Partial<HogQLQuery>)
+}
+
function sanitizeSourceQuery(sourceQuery: DataVisualizationNode): DataVisualizationNode {
const { connectionId: _ignoredConnectionId, ...sanitizedSourceQuery } = sourceQuery as LegacyDataVisualizationNode
@@ -890,6 +914,13 @@ export interface sqlEditorLogicActions {
openMaterializationModal: (view?: DataWarehouseSavedQuery) => {
view: DataWarehouseSavedQuery | undefined
}
+ openMetricFromUrl: (
+ metricName: string,
+ biEditorState: BIEditorState | null
+ ) => {
+ biEditorState: BIEditorState | null
+ metricName: string
+ }
reportAIQueryAccepted: () => {
value: true
}
@@ -1332,6 +1363,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}),
setMetricPrefill: (metricPrefill: MetricFormPrefill | null) => ({ metricPrefill }),
setEditingMetricName: (metricName: string | null) => ({ metricName }),
+ openMetricFromUrl: (metricName: string, biEditorState: BIEditorState | null) => ({ metricName, biEditorState }),
updateEditingMetric: true,
setMetricUpdating: (updating: boolean) => ({ updating }),
updateInsight: true,
@@ -2781,6 +2813,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}) as unknown as Record<string, unknown>,
})
captureBIEditorQuerySaved(biEditorState, 'metric', 'create')
+ metricsLogic.findMounted()?.actions.loadMetrics()
actions.setMetricPrefill(null)
lemonToast.success('Metric created')
router.actions.push(urls.dataCatalogMetric(metric.name))
@@ -2788,6 +2821,43 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
lemonToast.error(error.detail || 'Failed to create metric')
}
},
+ openMetricFromUrl: async ({ metricName, biEditorState }, breakpoint) => {
+ const openMetricTab = (sourceQuery: DataVisualizationNode, boundMetricName?: string): void => {
+ actions.createTab(
+ sourceQuery.source.query,
+ undefined,
+ undefined,
+ undefined,
+ boundMetricName,
+ biEditorState ?? undefined
+ )
+ actions.setQueryInput(sourceQuery.source.query)
+ actions.setSourceQuery(sourceQuery)
+ }
+ try {
+ // Validate before it reaches the request path: the value is interpolated
+ // into the URL unencoded, so a name containing "../" could otherwise
+ // traverse to a metric in another project. The name regex forbids slashes.
+ if (validateMetricName(metricName)) {
+ throw new Error('Invalid metric name')
+ }
+ const metric = await dataCatalogMetricsRetrieve(String(ApiConfig.getCurrentTeamId()), metricName)
+ breakpoint()
+ const metricSourceQuery = metricEditorSourceQuery(metric.definition)
+ if (!metricSourceQuery) {
+ throw new Error('Metric is not defined in SQL')
+ }
+ openMetricTab(metricSourceQuery, metric.name)
+ } catch (error) {
+ if (isBreakpoint(error as Error)) {
+ throw error
+ }
+ breakpoint()
+ // Invalid name, metric not found, or no access — open an unbound empty tab
+ // rather than binding an update target we couldn't verify.
+ openMetricTab(hogQLEditorSourceQuery())
+ }
+ },
updateEditingMetric: async () => {
if (!values.editingMetricName || values.metricUpdating) {
return
@@ -2806,6 +2876,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
)
captureBIEditorQuerySaved(biEditorState, 'metric', 'update')
+ metricsLogic.findMounted()?.actions.loadMetrics()
lemonToast.success('Metric updated')
router.actions.push(urls.dataCatalogMetric(values.editingMetricName))
} catch (error: any) {
@@ -3472,6 +3543,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
!searchParams.open_view &&
!searchParams.open_insight &&
!searchParams.open_draft &&
+ !searchParams.edit_metric &&
!searchParams.output_tab &&
!hashParams.q &&
!hashParams.c &&
@@ -3701,39 +3773,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
// a teammate's metric with arbitrary HogQL. Load the metric server-side and open
// its stored query, so the update target and its definition come from the same
// authenticated response.
- try {
- // Validate before it reaches the request path: the value is interpolated
- // into the URL unencoded, so a name containing "../" could otherwise
- // traverse to a metric in another project. The name regex forbids slashes.
- if (validateMetricName(searchParams.edit_metric)) {
- throw new Error('Invalid metric name')
- }
- const metric = await dataCatalogMetricsRetrieve(
- String(ApiConfig.getCurrentTeamId()),
- searchParams.edit_metric
- )
- const definition = metric.definition as Record<string, unknown> | null | undefined
- const metricQuery = typeof definition?.query === 'string' ? definition.query : ''
- actions.createTab(
- metricQuery,
- undefined,
- undefined,
- undefined,
- metric.name,
- biEditorStateFromUrl ?? undefined
- )
- } catch {
- // Invalid name, metric not found, or no access — open an unbound empty tab
- // rather than binding an update target we couldn't verify.
- actions.createTab(
- '',
- undefined,
- undefined,
- undefined,
- undefined,
- biEditorStateFromUrl ?? undefined
- )
- }
+ actions.openMetricFromUrl(searchParams.edit_metric, biEditorStateFromUrl)
tabAdded = true
} else if (searchParams.open_query) {
// kea-router decodes JSON-shaped URL values to objects — a node here carries
diff --git a/products/data_catalog/frontend/common.ts b/products/data_catalog/frontend/common.ts
index fc61eca85e4c..99b2fa27d2e6 100644
--- a/products/data_catalog/frontend/common.ts
+++ b/products/data_catalog/frontend/common.ts
@@ -1,5 +1,7 @@
export const METRIC_NAME_REGEX = /^[A-Za-z][A-Za-z0-9_]*$/
+export const HOGQL_METRIC_DEFINITION_KIND = 'HogQLQuery'
+
/** Values typed in the new metric modal, carried into the SQL editor's "Save as metric" dialog. */
export interface MetricFormPrefill {
name?: string
@@ -19,7 +21,7 @@ export function humanizeDefinitionKind(kind: string | null): string {
if (!kind) {
return 'Stub'
}
- if (kind === 'HogQLQuery') {
+ if (kind === HOGQL_METRIC_DEFINITION_KIND) {
return 'SQL'
}
if (kind === 'MarkdownDefinition') {
diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx
index 1b38a76b877e..4c32f61e84b2 100644
--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx
+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx
@@ -23,7 +23,7 @@ import { urls } from 'scenes/urls'
import { Breadcrumb, DataModelingEdge, DataModelingNode } from '~/types'
-import { validateMetricName } from './common'
+import { HOGQL_METRIC_DEFINITION_KIND, validateMetricName } from './common'
import { dataCatalogAgentSyncLogic } from './dataCatalogAgentSyncLogic'
import {
dataCatalogMetricsApproveCreate,
@@ -460,7 +460,7 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(
],
supportsMetricChecks: [
(s) => [s.metric],
- (metric: DataCatalogMetricApi | null): boolean => metric?.definition_kind === 'HogQLQuery',
+ (metric: DataCatalogMetricApi | null): boolean => metric?.definition_kind === HOGQL_METRIC_DEFINITION_KIND,
],
breadcrumbs: [
(s) => [s.metric, (_, props) => props.name],