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(data-warehouse): allow materializing a view at creation time (#66964)

Thiago Salvatorebbc43a18c863
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 065f2ae98794..31d83984fe71 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -2,12 +2,14 @@ import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { insightsApi } from 'scenes/insights/utils/api'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
import * as queryRunner from '~/queries/query'
import {
@@ -166,9 +168,11 @@ describe('sqlEditorLogic', () => {
let databaseLogic: ReturnType<typeof databaseTableListLogic.build>
const TAB_ID = '1'
let queryEndpointMock: jest.Mock
+ let materializeEndpointMock: jest.Mock
beforeEach(async () => {
queryEndpointMock = jest.fn(() => [200, { tables: {}, joins: [] }])
+ materializeEndpointMock = jest.fn(() => [200, {}])
useMocks({
get: {
'/api/environments/:team_id/insights/': ({ request }) => {
@@ -198,6 +202,21 @@ describe('sqlEditorLogic', () => {
},
post: {
'/api/environments/:team_id/query/': queryEndpointMock,
+ '/api/environments/:team_id/warehouse_saved_queries/': () => [
+ 200,
+ {
+ id: 'created-view-id',
+ name: 'Materialized view',
+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },
+ is_materialized: false,
+ latest_history_id: null,
+ sync_frequency: null,
+ status: null,
+ last_run_at: null,
+ latest_error: null,
+ },
+ ],
+ '/api/environments/:team_id/warehouse_saved_queries/:id/materialize/': materializeEndpointMock,
},
patch: {
'/api/user_home_settings/@me/': [200],
@@ -1571,4 +1590,51 @@ describe('sqlEditorLogic', () => {
expect([...(updatePayload.dashboards ?? [])].sort()).toEqual([...expected].sort())
})
})
+
+ describe('materialize on save', () => {
+ it.each([
+ { name: 'materializes the created view when materializeAfterSave is true', materialize: true },
+ { name: 'does not materialize when materializeAfterSave is false', materialize: false },
+ ])('$name', async ({ materialize }) => {
+ const viewsLogic = dataWarehouseViewsLogic()
+ viewsLogic.mount()
+
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+
+ logic.actions.createTab('SELECT 1')
+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
+ logic.actions.setQueryInput('SELECT 1')
+
+ // saveAsViewSubmit reads the editor's dataNodeLogic for inferred column types; in the
+ // app it's mounted by the visualization, so mount a matching one here.
+ const editorDataNodeLogic = dataNodeLogic({
+ key: logic.values.dataLogicKey,
+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },
+ })
+ editorDataNodeLogic.mount()
+
+ logic.actions.saveAsViewSubmit('Materialized view', materialize)
+
+ await expectLogic(viewsLogic).toDispatchActions(['createDataWarehouseSavedQuerySuccess'])
+ await expectLogic(viewsLogic).toFinishAllListeners()
+
+ if (materialize) {
+ expect(materializeEndpointMock).toHaveBeenCalledTimes(1)
+ // Guard against passing the wrong (or undefined) view id to the materialize call.
+ expect(materializeEndpointMock).toHaveBeenCalledWith(
+ expect.objectContaining({ params: expect.objectContaining({ id: 'created-view-id' }) })
+ )
+ } else {
+ expect(materializeEndpointMock).toHaveBeenCalledTimes(0)
+ }
+
+ editorDataNodeLogic.unmount()
+ viewsLogic.unmount()
+ })
+ })
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 182001d4acd9..bddbde48ce51 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -1312,6 +1312,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
viewName: values.activeTab?.name || '',
folderId: null,
isTest: false,
+ materializeAfterSave,
dagId: multiDagEnabled
? (values.dags.find((d) => d.id === values.selectedDagId)?.id ?? values.dags[0]?.id ?? null)
: undefined,
@@ -1402,6 +1403,21 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
)}
</LemonField>
)}
+ <LemonField name="materializeAfterSave" className="mt-2">
+ {({ value, onChange }) => (
+ <div className="flex items-center gap-2">
+ <LemonCheckbox
+ checked={value}
+ onChange={onChange}
+ data-attr="sql-editor-input-save-view-materialize"
+ label="Materialize this view"
+ />
+ <Tooltip title="Pre-compute the results into a table for faster queries. Syncs daily by default — you can adjust the frequency later in the view's materialization settings.">
+ <span className="text-muted cursor-pointer">&#9432;</span>
+ </Tooltip>
+ </div>
+ )}
+ </LemonField>
<SaveTargetCycler
candidates={candidates}
onChange={(q) => {
@@ -1414,10 +1430,16 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
viewName: validateSavedQueryName,
dagId: (dagId) => (multiDagEnabled && !dagId ? 'Please select a DAG' : undefined),
},
- onSubmit: async ({ viewName, dagId, folderId, isTest }) => {
+ onSubmit: async ({
+ viewName,
+ dagId,
+ folderId,
+ isTest,
+ materializeAfterSave: shouldMaterialize,
+ }) => {
await asyncActions.saveAsViewSubmit(
viewName,
- materializeAfterSave,
+ shouldMaterialize ?? false,
fromDraft,
dagId,
folderId,