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.

refactor(sql-editor): split editor scene logic (#57141)

Marius Andrab4682f746915
diff --git a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
index 93662ca934bd..5f73bf2c898a 100644
--- a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
+++ b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx
@@ -18,13 +18,15 @@ import { SyncMoreNotice } from './SyncMoreNotice'
export const DatabaseTree = memo(function DatabaseTree({
databaseTreeRef,
+ tabId,
}: {
databaseTreeRef: React.RefObject<HTMLDivElement>
+ tabId: string
}): JSX.Element | null {
const scrollContainerRef = useRef<HTMLDivElement | null>(null)
const { databaseTreeWidth, databaseTreeResizerProps, isDatabaseTreeCollapsed, databaseTreeWillCollapse } =
useValues(editorSizingLogic)
- const { selectedConnectionId, selectedDirectSource } = useValues(sqlEditorLogic)
+ const { selectedConnectionId, selectedDirectSource } = useValues(sqlEditorLogic({ tabId }))
const { toggleDatabaseTreeCollapsed, setDatabaseTreeCollapsed } = useActions(editorSizingLogic)
const searchPlaceholder = selectedConnectionId
@@ -59,7 +61,7 @@ export const DatabaseTree = memo(function DatabaseTree({
>
<IconSidebarClose className="size-4 text-tertiary rotate-180" />
</ButtonPrimitive>
- <ConnectionSelector />
+ <ConnectionSelector tabId={tabId} />
</div>
<DatabaseSearchField placeholder={searchPlaceholder} />
</div>
diff --git a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx
index b6b1e4d9970a..771f1015e751 100644
--- a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx
@@ -12,6 +12,7 @@ import {
CONFIGURE_SOURCES,
POSTHOG_WAREHOUSE,
connectionSelectorLogic,
+ getConnectionSelectorValue,
} from './connectionSelectorLogic'
import { sqlEditorLogic } from './sqlEditorLogic'
@@ -19,12 +20,21 @@ const sourceIcon = (src: string): JSX.Element => (
<img src={src} alt="" width={16} height={16} className="object-contain rounded" />
)
-export function ConnectionSelector(): JSX.Element | null {
- const { sourceQuery, selectedConnectionId } = useValues(sqlEditorLogic)
- const { connectionSelectOptions, connectionSelectorValue } = useValues(
- connectionSelectorLogic({ selectedConnectionId })
+interface ConnectionSelectorProps {
+ tabId: string
+}
+
+export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Element | null {
+ const logic = sqlEditorLogic({ tabId })
+ const { sourceQuery, selectedConnectionId } = useValues(logic)
+ const { connectionOptions, connectionOptionsLoading, connectionSelectOptions } =
+ useValues(connectionSelectorLogic())
+ const { setSourceQuery, syncUrlWithQuery } = useActions(logic)
+ const connectionSelectorValue = getConnectionSelectorValue(
+ connectionOptions,
+ connectionOptionsLoading,
+ selectedConnectionId
)
- const { setSourceQuery, syncUrlWithQuery } = useActions(sqlEditorLogic)
// Strip the legacy top-level connectionId so source.connectionId stays canonical.
const { connectionId: _legacyConnectionId, ...sourceQueryWithoutLegacyConnectionId } =
sourceQuery as typeof sourceQuery & {
diff --git a/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx b/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx
index 7b2186926ff4..92fdafd853c0 100644
--- a/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx
@@ -1,25 +1,33 @@
import './EditorScene.scss'
+import { useActions } from 'kea'
+
import { AccessDenied } from 'lib/components/AccessDenied'
import { userHasAccess } from 'lib/utils/accessControlUtils'
import { SceneExport } from 'scenes/sceneTypes'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { editorSceneLogic } from './editorSceneLogic'
import { SQLEditor } from './SQLEditor'
-import { sqlEditorLogic } from './sqlEditorLogic'
import { SQLEditorMode } from './sqlEditorModes'
export const scene: SceneExport = {
- logic: sqlEditorLogic,
+ logic: editorSceneLogic,
component: EditorScene,
}
export function EditorScene({ tabId }: { tabId?: string }): JSX.Element {
+ const resolvedTabId = tabId ?? 'default'
+ const { shareTab } = useActions(editorSceneLogic({ tabId: resolvedTabId }))
+
if (!userHasAccess(AccessControlResourceType.WarehouseObjects, AccessControlLevel.Viewer)) {
return (
<AccessDenied reason="You don't have access to Data warehouse tables & views, so the SQL editor isn't available." />
)
}
- return <SQLEditor tabId={tabId} mode={SQLEditorMode.FullScene} showDatabaseTree={true} />
+
+ return (
+ <SQLEditor tabId={resolvedTabId} mode={SQLEditorMode.FullScene} showDatabaseTree={true} onShareTab={shareTab} />
+ )
}
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 7eb2b044c5f8..30816076172d 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -399,7 +399,7 @@ interface ResultsActionsProps {
exportContext: ExportContext | undefined
hasQueryInput: boolean
isEmbeddedMode: boolean
- onShareTab: () => void
+ onShareTab?: () => void
}
function ResultsActions({
@@ -457,7 +457,7 @@ function ResultsActions({
/>
</Tooltip>
)}
- {!isEmbeddedMode && (
+ {!isEmbeddedMode && onShareTab && (
<Tooltip title="Share your current query">
<LemonButton
id="sql-editor-share"
@@ -482,7 +482,7 @@ interface OutputActionsProps {
hasQueryInput: boolean
isEmbeddedMode: boolean
settingsOpen: boolean
- onShareTab: () => void
+ onShareTab?: () => void
onToggleChartSettingsPanel: () => void
}
@@ -528,14 +528,15 @@ function OutputActions({
interface OutputPaneProps {
tabId: string
showToolbar?: boolean
+ onShareTab?: () => void
}
-export function OutputPane({ tabId, showToolbar = true }: OutputPaneProps): JSX.Element {
+export function OutputPane({ tabId, showToolbar = true, onShareTab }: OutputPaneProps): JSX.Element {
const { activeTab } = useValues(outputPaneLogic)
const { setActiveTab } = useActions(outputPaneLogic)
const { sourceQuery, exportContext, insightLoading, hasQueryInput, isEmbeddedMode } = useValues(sqlEditorLogic)
- const { setSourceQuery, shareTab } = useActions(sqlEditorLogic)
+ const { setSourceQuery } = useActions(sqlEditorLogic)
const { isDarkModeOn } = useValues(themeLogic)
const {
response: dataNodeResponse,
@@ -750,7 +751,7 @@ export function OutputPane({ tabId, showToolbar = true }: OutputPaneProps): JSX.
hasQueryInput,
isEmbeddedMode,
settingsOpen: isChartSettingsPanelOpen,
- onShareTab: shareTab,
+ onShareTab,
onToggleChartSettingsPanel: toggleVisualizationSettingsPanel,
}
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.stories.tsx b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.stories.tsx
index 3c8b040bab93..f8c62051aaf5 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.stories.tsx
@@ -5,6 +5,7 @@ import { useEffect } from 'react'
import { mswDecorator } from '~/mocks/browser'
import { ActivityScope } from '~/types'
+import { editorSceneLogic } from './editorSceneLogic'
import { QueryHistoryModal } from './QueryHistoryModal'
import { sqlEditorLogic } from './sqlEditorLogic'
@@ -12,7 +13,8 @@ const STORY_TAB_ID = 'story-query-history'
// Opens the modal immediately so the story renders it in the open state
function OpenQueryHistoryModal(): JSX.Element {
- const { openHistoryModal, updateTab } = useActions(sqlEditorLogic({ tabId: STORY_TAB_ID }))
+ const { openHistoryModal } = useActions(editorSceneLogic({ tabId: STORY_TAB_ID }))
+ const { updateTab } = useActions(sqlEditorLogic({ tabId: STORY_TAB_ID }))
useEffect(() => {
updateTab({
uri: { toString: () => 'story-uri' } as any,
@@ -22,8 +24,10 @@ function OpenQueryHistoryModal(): JSX.Element {
openHistoryModal()
}, [openHistoryModal, updateTab])
return (
- <BindLogic logic={sqlEditorLogic} props={{ tabId: STORY_TAB_ID }}>
- <QueryHistoryModal />
+ <BindLogic logic={editorSceneLogic} props={{ tabId: STORY_TAB_ID }}>
+ <BindLogic logic={sqlEditorLogic} props={{ tabId: STORY_TAB_ID }}>
+ <QueryHistoryModal />
+ </BindLogic>
</BindLogic>
)
}
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx
index 2aee31bac6ac..64b766815685 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx
@@ -14,8 +14,8 @@ import { TZLabel } from 'lib/components/TZLabel'
import { PaginationControl, usePagination } from 'lib/lemon-ui/PaginationControl'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { editorSceneLogic } from './editorSceneLogic'
import { queryHistoryLogic } from './queryHistoryLogic'
-import { sqlEditorLogic } from './sqlEditorLogic'
function QueryHistoryLogRow({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {
const [isExpanded, setIsExpanded] = useState(false)
@@ -138,9 +138,8 @@ function QueryHistoryLog({ id }: { id?: number | string }): JSX.Element {
}
export function QueryHistoryModal(): JSX.Element {
- const { isHistoryModalOpen } = useValues(sqlEditorLogic)
- const { closeHistoryModal } = useActions(sqlEditorLogic)
- const { editingView } = useValues(sqlEditorLogic)
+ const { editingView, isHistoryModalOpen } = useValues(editorSceneLogic)
+ const { closeHistoryModal } = useActions(editorSceneLogic)
return (
<LemonModal title="View history" isOpen={isHistoryModalOpen} onClose={closeHistoryModal} width={800}>
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index 94651d17e589..d15b3b817998 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -46,6 +46,7 @@ interface QueryWindowProps {
runQueryLoading?: boolean
runQueryDisabledReason?: string
runQueryTooltip?: string
+ onShareTab?: () => void
}
export function QueryWindow({
@@ -60,8 +61,10 @@ export function QueryWindow({
runQueryLoading,
runQueryDisabledReason,
runQueryTooltip,
+ onShareTab,
}: QueryWindowProps): JSX.Element {
const codeEditorKey = `hogql-editor-${tabId}`
+ const logic = sqlEditorLogic({ tabId })
const {
queryInput,
@@ -73,7 +76,7 @@ export function QueryWindow({
activeQueryOffset,
selectedConnectionId,
sendRawQueryEnabled,
- } = useValues(sqlEditorLogic)
+ } = useValues(logic)
const {
setQueryInput,
@@ -84,9 +87,9 @@ export function QueryWindow({
setMetadataLoading,
setSendRawQuery,
openMaterializationModal,
- } = useActions(sqlEditorLogic)
+ } = useActions(logic)
- const { setSuggestedQueryInput, reportAIQueryPromptOpen } = useActions(sqlEditorLogic)
+ const { setSuggestedQueryInput, reportAIQueryPromptOpen } = useActions(logic)
const vimModeFeatureEnabled = useFeatureFlag('SQL_EDITOR_VIM_MODE')
const { editorVimModeEnabled } = useValues(userPreferencesLogic)
const { setEditorVimModeEnabled } = useActions(userPreferencesLogic)
@@ -166,7 +169,7 @@ export function QueryWindow({
runQueryDisabledReason={runQueryDisabledReason}
runQueryTooltip={runQueryTooltip}
/>
- <CollapsedConnectionSelector mode={mode} />
+ <CollapsedConnectionSelector tabId={tabId} mode={mode} />
<LemonDivider vertical />
<QueryVariablesMenu
disabledReason={editingView ? 'Variables are not allowed in views.' : undefined}
@@ -285,7 +288,7 @@ export function QueryWindow({
/>
) : null}
- {showOutputPanel ? <InternalQueryWindow tabId={tabId} /> : null}
+ {showOutputPanel ? <InternalQueryWindow tabId={tabId} onShareTab={onShareTab} /> : null}
</div>
)
}
@@ -425,22 +428,28 @@ function RunButton({
)
}
-const InternalQueryWindow = memo(function InternalQueryWindow({ tabId }: { tabId: string }): JSX.Element | null {
+const InternalQueryWindow = memo(function InternalQueryWindow({
+ tabId,
+ onShareTab,
+}: {
+ tabId: string
+ onShareTab?: () => void
+}): JSX.Element | null {
const { finishedLoading } = useValues(sqlEditorLogic)
if (finishedLoading) {
return null
}
- return <OutputPane tabId={tabId} />
+ return <OutputPane tabId={tabId} onShareTab={onShareTab} />
})
-function CollapsedConnectionSelector({ mode }: { mode?: SQLEditorMode }): JSX.Element | null {
+function CollapsedConnectionSelector({ tabId, mode }: { tabId: string; mode?: SQLEditorMode }): JSX.Element | null {
const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)
if (!isDatabaseTreeCollapsed || (mode && mode !== SQLEditorMode.FullScene)) {
return null
}
- return <ConnectionSelector />
+ return <ConnectionSelector tabId={tabId} />
}
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 0c87c0cef66f..c9a6fa05932a 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -33,6 +33,8 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'
import { ViewLinkModal } from '../ViewLinkModal'
+import { connectionSelectorLogic } from './connectionSelectorLogic'
+import { editorSceneLogic } from './editorSceneLogic'
import { editorSizingLogic } from './editorSizingLogic'
import { QueryInfo } from './output-pane-tabs/QueryInfo'
import { OutputPane } from './OutputPane'
@@ -59,6 +61,7 @@ interface SQLEditorProps {
runQueryLoading?: boolean
runQueryDisabledReason?: string
runQueryTooltip?: string
+ onShareTab?: () => void
}
export function SQLEditor({
@@ -72,6 +75,7 @@ export function SQLEditor({
runQueryLoading,
runQueryDisabledReason,
runQueryTooltip,
+ onShareTab,
}: SQLEditorProps): JSX.Element {
const ref = useRef(null)
const navigatorRef = useRef(null)
@@ -83,7 +87,7 @@ export function SQLEditor({
const shouldShowDatabaseTree = showDatabaseTree ?? hasShownDatabaseTree
const showQueryPanel = panel !== SQLEditorPanel.Output
const showOutputPanel = panel !== SQLEditorPanel.Query
- const showSceneTitle = panel === SQLEditorPanel.Full
+ const showSceneTitle = panel === SQLEditorPanel.Full && mode === SQLEditorMode.FullScene
const showDatabaseTreePanel = showQueryPanel && shouldShowDatabaseTree
const editorSizingLogicProps = useMemo(
@@ -178,6 +182,7 @@ export function SQLEditor({
const { loadData } = useActions(dataNodeLogic(dataNodeLogicProps))
useAttachedLogic(dataNodeLogic(dataNodeLogicProps), logic)
+ useAttachedLogic(connectionSelectorLogic(), logic)
const variablesLogicProps: VariablesLogicProps = {
key: dataVisualizationLogicProps.key,
@@ -200,7 +205,11 @@ export function SQLEditor({
<VariablesQuerySync />
{panel === SQLEditorPanel.Output ? (
<div className="flex h-full min-h-0 flex-col overflow-hidden">
- <OutputPane tabId={tabId || ''} showToolbar={showOutputToolbar} />
+ <OutputPane
+ tabId={tabId || ''}
+ showToolbar={showOutputToolbar}
+ onShareTab={onShareTab}
+ />
</div>
) : (
<BindLogic logic={editorSizingLogic} props={editorSizingLogicProps}>
@@ -208,7 +217,10 @@ export function SQLEditor({
{showSceneTitle ? <SQLEditorSceneTitle /> : null}
<div className="flex min-h-0 flex-1">
{showDatabaseTreePanel && (
- <DatabaseTree databaseTreeRef={databaseTreeRef} />
+ <DatabaseTree
+ databaseTreeRef={databaseTreeRef}
+ tabId={tabId || ''}
+ />
)}
<div
data-attr="editor-scene"
@@ -229,6 +241,7 @@ export function SQLEditor({
runQueryLoading={runQueryLoading}
runQueryDisabledReason={runQueryDisabledReason}
runQueryTooltip={runQueryTooltip}
+ onShareTab={onShareTab}
/>
</div>
</div>
@@ -276,6 +289,7 @@ function MaterializationModal({ tabId }: { tabId: string }): JSX.Element {
}
function SQLEditorSceneTitle(): JSX.Element | null {
+ const { titleSectionProps, updateInsightButtonEnabled, saveAsMenuItems } = useValues(editorSceneLogic)
const {
queryInput,
editingView,
@@ -284,14 +298,11 @@ function SQLEditorSceneTitle(): JSX.Element | null {
sourceQuery,
changesToSave,
inProgressViewEdits,
- isEmbeddedMode,
- titleSectionProps,
- updateInsightButtonEnabled,
- saveAsMenuItems,
isSourceQueryLastRun,
isMultiQuery,
featureFlags,
} = useValues(sqlEditorLogic)
+ const { openHistoryModal } = useActions(editorSceneLogic)
const {
updateView,
updateInsight,
@@ -299,7 +310,6 @@ function SQLEditorSceneTitle(): JSX.Element | null {
saveAsInsight,
saveAsView,
saveAsEndpoint,
- openHistoryModal,
setSuggestedQueryInput,
reportAIQueryPromptOpen,
} = useActions(sqlEditorLogic)
@@ -382,10 +392,6 @@ function SQLEditorSceneTitle(): JSX.Element | null {
return [undefined, IconDownload]
}, [updatingDataWarehouseSavedQuery, changesToSave, response, isMultiQuery])
- if (isEmbeddedMode) {
- return null
- }
-
const isMaterializedView = editingView?.is_materialized === true
const closeObjectTooltip = editingInsight
? 'Close this insight and reset the SQL editor to an unsaved query without clearing your SQL or visualization settings.'
diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts
index 16bd99f8d389..b28ba4e78cd0 100644
--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts
@@ -5,7 +5,12 @@ import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
-import { connectionSelectorLogic, POSTHOG_WAREHOUSE } from './connectionSelectorLogic'
+import {
+ connectionSelectorLogic,
+ getConnectionSelectorValue,
+ LOADING_CONNECTIONS,
+ POSTHOG_WAREHOUSE,
+} from './connectionSelectorLogic'
describe('connectionSelectorLogic', () => {
let logic: ReturnType<typeof connectionSelectorLogic.build>
@@ -27,13 +32,12 @@ describe('connectionSelectorLogic', () => {
})
it('loads connection options on mount', async () => {
- logic = connectionSelectorLogic({ selectedConnectionId: undefined })
+ logic = connectionSelectorLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
expect(api.externalDataSources.connections).toHaveBeenCalledTimes(1)
- expect(logic.values.connectionSelectorValue).toEqual(POSTHOG_WAREHOUSE)
expect(logic.values.connectionSelectOptions[0].options).toEqual(
expect.arrayContaining([
expect.objectContaining({ value: POSTHOG_WAREHOUSE }),
@@ -48,4 +52,22 @@ describe('connectionSelectorLogic', () => {
expect.arrayContaining([expect.not.objectContaining({ managementUrl: expect.anything() })])
)
})
+
+ it('derives the selected connection value from sql editor state', async () => {
+ expect(getConnectionSelectorValue(null, true, undefined)).toEqual(LOADING_CONNECTIONS)
+ expect(
+ getConnectionSelectorValue(
+ [{ id: 'conn-123', prefix: 'warehouse', engine: 'postgres' }] as any,
+ false,
+ 'conn-123'
+ )
+ ).toEqual('conn-123')
+ expect(
+ getConnectionSelectorValue(
+ [{ id: 'conn-123', prefix: 'warehouse', engine: 'postgres' }] as any,
+ false,
+ 'missing'
+ )
+ ).toEqual(POSTHOG_WAREHOUSE)
+ })
})
diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
index a6f3daba7f9c..02bb6aec5236 100644
--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts
@@ -1,4 +1,4 @@
-import { afterMount, connect, kea, listeners, path, props, selectors } from 'kea'
+import { afterMount, connect, kea, listeners, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
@@ -19,10 +19,6 @@ export const LOADING_CONNECTIONS = '__loading_connections__'
export const ADD_POSTGRES_DIRECT_CONNECTION = '__add_postgres_direct_connection__'
export const CONFIGURE_SOURCES = '__configure_sources__'
-export interface ConnectionSelectorLogicProps {
- selectedConnectionId?: string
-}
-
export interface ConnectionSelectOption {
value: string
label: string
@@ -39,9 +35,24 @@ function getConnectionEngine(source: Pick<ExternalDataSourceConnectionOption, 'e
return source.engine === 'duckdb' ? 'duckdb' : 'postgres'
}
+export function getConnectionSelectorValue(
+ connectionOptions: ExternalDataSourceConnectionOption[] | null,
+ connectionOptionsLoading: boolean,
+ selectedConnectionId: string | undefined
+): string {
+ if (connectionOptionsLoading) {
+ return LOADING_CONNECTIONS
+ }
+
+ if (selectedConnectionId && (connectionOptions ?? []).some((source) => source.id === selectedConnectionId)) {
+ return selectedConnectionId
+ }
+
+ return POSTHOG_WAREHOUSE
+}
+
export const connectionSelectorLogic = kea<connectionSelectorLogicType>([
path(['scenes', 'data-warehouse', 'editor', 'connectionSelectorLogic']),
- props({ selectedConnectionId: undefined } as ConnectionSelectorLogicProps),
connect(() => ({
actions: [sourcesDataLogic, ['loadSourcesSuccess']],
})),
@@ -103,27 +114,6 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([
]
},
],
- connectionSelectorValue: [
- (s) => [s.connectionOptions, s.connectionOptionsLoading, (_, props) => props.selectedConnectionId],
- (
- connectionOptions: ExternalDataSourceConnectionOption[] | null,
- connectionOptionsLoading: boolean,
- selectedConnectionId: string | undefined
- ): string => {
- if (connectionOptionsLoading) {
- return LOADING_CONNECTIONS
- }
-
- if (
- selectedConnectionId &&
- (connectionOptions ?? []).some((source) => source.id === selectedConnectionId)
- ) {
- return selectedConnectionId
- }
-
- return POSTHOG_WAREHOUSE
- },
- ],
}),
afterMount(({ actions, values }) => {
if (values.connectionOptions === null && !values.connectionOptionsLoading) {
diff --git a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
index 1948f61009e1..61f21f032f75 100644
--- a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
@@ -1,11 +1,41 @@
-import { actions, kea, listeners, path, props, selectors } from 'kea'
-import posthog from 'posthog-js'
+import equal from 'fast-deep-equal'
+import { actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
+import { FEATURE_FLAGS } from 'lib/constants'
import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
+import { removeUndefinedAndNull } from 'lib/utils'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
+import { DataVisualizationNode, FileSystemIconType, HogQLFilters, NodeKind } from '~/queries/schema/schema-general'
+import { Breadcrumb } from '~/types'
import type { editorSceneLogicType } from './editorSceneLogicType'
+import {
+ getCurrentVisualizationQuery,
+ normalizeFiltersForUrl,
+ sqlEditorLogic,
+ toDataVisualizationNode,
+} from './sqlEditorLogic'
+
+export interface SaveAsMenuItem {
+ action: 'insight' | 'endpoint' | 'view'
+ label: string
+ dataAttr?: string
+}
+
+function setFiltersHashParam(url: URL, filters: HogQLFilters | null | undefined): void {
+ const normalizedFilters = normalizeFiltersForUrl(filters)
+ if (!normalizedFilters) {
+ return
+ }
+
+ const hashParams = new URLSearchParams(url.hash ? url.hash.slice(1) : '')
+ hashParams.set('filters', JSON.stringify(normalizedFilters))
+ url.hash = hashParams.toString()
+}
export const renderTableCount = (count: undefined | number): null | JSX.Element => {
if (!count) {
@@ -32,24 +62,278 @@ export const editorSceneLogic = kea<editorSceneLogicType>([
path(['data-warehouse', 'editor', 'editorSceneLogic']),
props({} as EditorSceneLogicProps),
tabAwareScene(),
+ connect((props: EditorSceneLogicProps) => ({
+ values: [
+ sqlEditorLogic({ tabId: props.tabId }),
+ [
+ 'activeTab',
+ 'dashboardId',
+ 'dataLogicKey',
+ 'editingInsight',
+ 'editingView',
+ 'editorSource',
+ 'featureFlags',
+ 'insightLoading',
+ 'queryInput',
+ 'sourceQuery',
+ 'viewLoading',
+ ],
+ ],
+ })),
actions({
- reportAIQueryPrompted: true,
- reportAIQueryAccepted: true,
- reportAIQueryRejected: true,
- reportAIQueryPromptOpen: true,
+ shareTab: true,
+ openHistoryModal: true,
+ closeHistoryModal: true,
}),
- listeners(() => ({
- reportAIQueryPrompted: () => {
- posthog.capture('ai_query_prompted')
- },
- reportAIQueryAccepted: () => {
- posthog.capture('ai_query_accepted')
- },
- reportAIQueryRejected: () => {
- posthog.capture('ai_query_rejected')
- },
- reportAIQueryPromptOpen: () => {
- posthog.capture('ai_query_prompt_open')
+ reducers({
+ isHistoryModalOpen: [
+ false as boolean,
+ {
+ openHistoryModal: () => true,
+ closeHistoryModal: () => false,
+ },
+ ],
+ }),
+ selectors({
+ breadcrumbs: [
+ (s) => [s.activeTab],
+ (activeTab): Breadcrumb[] => {
+ const { draft, insight, view } = activeTab || {}
+ const first = {
+ key: Scene.SQLEditor,
+ name: 'SQL query',
+ to: urls.sqlEditor(),
+ iconType: 'sql_editor' as FileSystemIconType,
+ }
+ if (view) {
+ return [
+ {
+ key: view.id,
+ name: view.name,
+ path: urls.sqlEditor({ view_id: view.id }),
+ iconType: 'sql_editor',
+ },
+ ]
+ } else if (insight) {
+ return [
+ first,
+ {
+ key: insight.id,
+ name: insight.name || insight.derived_name || 'Untitled',
+ path: urls.sqlEditor({
+ insightShortId: insight.short_id,
+ }),
+ iconType: 'sql_editor',
+ },
+ ]
+ } else if (draft) {
+ return [
+ first,
+ {
+ key: draft.id,
+ name: draft.name || 'Untitled',
+ path: urls.sqlEditor({ draftId: draft.id }),
+ iconType: 'sql_editor',
+ },
+ ]
+ }
+ return [first]
+ },
+ ],
+ titleSectionProps: [
+ (s) => [
+ s.editingInsight,
+ s.insightLoading,
+ s.editingView,
+ s.viewLoading,
+ s.editorSource,
+ s.dashboardId,
+ s.activeTab,
+ ],
+ (editingInsight, insightLoading, editingView, viewLoading, editorSource, dashboardId, activeTab) => {
+ if (editingInsight) {
+ const forceBackTo: Breadcrumb = dashboardId
+ ? {
+ key: 'dashboard',
+ name: 'Back to dashboard',
+ path: urls.dashboard(dashboardId),
+ iconType: 'dashboard',
+ }
+ : {
+ key: editingInsight.short_id,
+ name: 'Back to insight',
+ path: urls.insightView(editingInsight.short_id),
+ iconType: 'insight/hog',
+ }
+
+ return {
+ forceBackTo,
+ name: editingInsight.name || editingInsight.derived_name || 'Untitled',
+ resourceType: { type: 'insight/hog' },
+ }
+ }
+
+ if (insightLoading) {
+ return {
+ name: 'Loading insight...',
+ resourceType: { type: 'insight/hog' },
+ }
+ }
+
+ if (editingView) {
+ return {
+ name: editingView.name,
+ resourceType: {
+ type: editingView.is_materialized ? 'matview' : 'view',
+ },
+ }
+ }
+
+ if (viewLoading) {
+ return {
+ name: 'Loading view...',
+ resourceType: { type: 'view' },
+ }
+ }
+
+ if (!activeTab) {
+ const searchParams = new URLSearchParams(window.location.search)
+ const hashParams = new URLSearchParams(window.location.hash.slice(1))
+ if (searchParams.get('open_view') || hashParams.get('view')) {
+ return {
+ name: 'Loading view...',
+ resourceType: { type: 'view' },
+ }
+ }
+
+ if (searchParams.get('open_insight') || hashParams.get('insight')) {
+ return {
+ name: 'Loading insight...',
+ resourceType: { type: 'insight/hog' },
+ }
+ }
+ }
+
+ if (editorSource === 'endpoint') {
+ const forceBackTo: Breadcrumb = {
+ key: 'endpoints',
+ name: 'Endpoints',
+ path: urls.endpoints(),
+ iconType: 'endpoints',
+ }
+
+ return {
+ forceBackTo,
+ name: 'New endpoint',
+ resourceType: { type: 'sql_editor' },
+ }
+ }
+
+ if (dashboardId) {
+ const forceBackTo: Breadcrumb = {
+ key: 'dashboard',
+ name: 'Back to dashboard',
+ path: urls.dashboard(dashboardId),
+ iconType: 'dashboard',
+ }
+
+ return {
+ forceBackTo,
+ name: 'New SQL query',
+ resourceType: { type: 'sql_editor' },
+ }
+ }
+
+ return {
+ name: 'New SQL query',
+ resourceType: { type: 'sql_editor' },
+ }
+ },
+ ],
+ saveAsMenuItems: [
+ (s) => [s.editorSource, s.dashboardId, s.featureFlags],
+ (editorSource, dashboardId, featureFlags): { primary: SaveAsMenuItem; secondary: SaveAsMenuItem[] } => {
+ const endpointsEnabled = !!featureFlags[FEATURE_FLAGS.ENDPOINTS]
+ const saveAsInsightItem: SaveAsMenuItem = {
+ action: 'insight',
+ label: dashboardId ? 'Save & add to dashboard' : 'Save as insight',
+ }
+ const saveAsEndpointItem: SaveAsMenuItem = {
+ action: 'endpoint',
+ label: 'Save as endpoint',
+ }
+ const saveAsViewItem: SaveAsMenuItem = {
+ action: 'view',
+ label: 'Save as view',
+ dataAttr: 'sql-editor-save-view-button',
+ }
+
+ if (editorSource === 'endpoint' && endpointsEnabled) {
+ return {
+ primary: saveAsEndpointItem,
+ secondary: [saveAsInsightItem, saveAsViewItem],
+ }
+ }
+
+ return {
+ primary: saveAsInsightItem,
+ secondary: endpointsEnabled ? [saveAsEndpointItem, saveAsViewItem] : [saveAsViewItem],
+ }
+ },
+ ],
+ updateInsightButtonEnabled: [
+ (s) => [s.sourceQuery, s.activeTab, s.editingInsight, s.dataLogicKey],
+ (sourceQuery, activeTab, editingInsight, dataLogicKey) => {
+ if (!editingInsight?.query) {
+ return false
+ }
+
+ const updatedName = activeTab?.name !== editingInsight.name
+ const currentVisualizationQuery = getCurrentVisualizationQuery(dataLogicKey, sourceQuery)
+
+ const sourceQueryWithoutUndefinedAndNullKeys = removeUndefinedAndNull(currentVisualizationQuery)
+ // Normalize so DataTableNode-based insights don't look "changed" immediately after load.
+ const editingInsightQuery = toDataVisualizationNode(editingInsight.query) ?? editingInsight.query
+
+ return (
+ updatedName ||
+ !equal(sourceQueryWithoutUndefinedAndNullKeys, removeUndefinedAndNull(editingInsightQuery))
+ )
+ },
+ ],
+ }),
+ listeners(({ values }) => ({
+ shareTab: () => {
+ const { activeTab, queryInput, sourceQuery } = values
+ if (!activeTab) {
+ return
+ }
+
+ const currentUrl = new URL(window.location.href)
+ const shareUrl = new URL(currentUrl.origin + currentUrl.pathname)
+
+ if (activeTab.insight) {
+ shareUrl.searchParams.set('open_insight', activeTab.insight.short_id)
+
+ if (activeTab.insight.query?.kind === NodeKind.DataVisualizationNode) {
+ const query = (activeTab.insight.query as DataVisualizationNode).source.query
+ if (queryInput !== query) {
+ shareUrl.searchParams.set('open_query', queryInput ?? '')
+ }
+ }
+ } else if (activeTab.view) {
+ shareUrl.searchParams.set('open_view', activeTab.view.id)
+
+ if (queryInput !== activeTab.view.query?.query) {
+ shareUrl.searchParams.set('open_query', queryInput ?? '')
+ }
+ } else {
+ shareUrl.searchParams.set('open_query', queryInput ?? '')
+ }
+
+ setFiltersHashParam(shareUrl, sourceQuery.source.filters)
+
+ void copyToClipboard(shareUrl.toString(), 'share link')
},
})),
selectors({
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 1b469f5b0523..868ef534eb79 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -18,6 +18,7 @@ import {
import { initKeaTests } from '~/test/init'
import { ChartDisplayType, InsightShortId, QueryBasedInsightModel } from '~/types'
+import { editorSceneLogic } from './editorSceneLogic'
import { OutputTab } from './outputPaneLogic'
import { activeTabMatchesUrlTarget, getDisplayTypeToSaveInsight, sqlEditorLogic } from './sqlEditorLogic'
@@ -159,6 +160,7 @@ function createMockEditor(): any {
describe('sqlEditorLogic', () => {
let logic: ReturnType<typeof sqlEditorLogic.build>
+ let editorRootLogic: ReturnType<typeof editorSceneLogic.build> | undefined
let databaseLogic: ReturnType<typeof databaseTableListLogic.build>
const TAB_ID = '1'
let queryEndpointMock: jest.Mock
@@ -184,6 +186,11 @@ describe('sqlEditorLogic', () => {
}
return [404]
},
+ '/api/environments/:team_id/data_modeling_dags/': { results: [] },
+ '/api/environments/:team_id/data_modeling_nodes/': { results: [] },
+ '/api/environments/:team_id/data_modeling_edges/': { results: [] },
+ '/api/environments/:team_id/data_modeling_jobs/recent/': [],
+ '/api/environments/:team_id/data_modeling_jobs/running/': [],
'/api/environments/:team_id/lineage/get_upstream/': { nodes: [], edges: [] },
'/api/user_home_settings/@me/': {},
},
@@ -210,6 +217,8 @@ describe('sqlEditorLogic', () => {
})
afterEach(() => {
+ editorRootLogic?.unmount()
+ editorRootLogic = undefined
logic?.unmount()
databaseLogic?.unmount()
})
@@ -366,10 +375,12 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
window.history.replaceState({}, '', `${urls.sqlEditor()}?open_view=test-view`)
- expect(logic.values.titleSectionProps.name).toEqual('Loading view...')
+ expect(editorRootLogic.values.titleSectionProps.name).toEqual('Loading view...')
})
it('shows loading insight title when opening an insight from URL before insight loads', async () => {
@@ -379,10 +390,12 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
window.history.replaceState({}, '', `${urls.sqlEditor()}?open_insight=${MOCK_INSIGHT_SHORT_ID}`)
- expect(logic.values.titleSectionProps.name).toEqual('Loading insight...')
+ expect(editorRootLogic.values.titleSectionProps.name).toEqual('Loading insight...')
})
it('closes an insight into an unsaved query without clearing SQL or visualization settings', async () => {
@@ -392,6 +405,8 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
window.history.replaceState(
{},
@@ -414,14 +429,14 @@ describe('sqlEditorLogic', () => {
editingInsight: null,
insightLoading: false,
queryInput: MOCK_INSIGHT_QUERY.source.query,
- titleSectionProps: partial({
- name: 'New SQL query',
- }),
sourceQuery: partial({
display: ChartDisplayType.BoldNumber,
}),
})
+ expect(editorRootLogic.values.titleSectionProps).toMatchObject({
+ name: 'New SQL query',
+ })
expect(window.location.hash).not.toContain('insight')
expect(window.location.search).not.toContain('open_insight')
})
@@ -433,6 +448,8 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
window.history.replaceState(
{},
@@ -459,14 +476,14 @@ describe('sqlEditorLogic', () => {
editingView: undefined,
viewLoading: false,
queryInput: MOCK_VIEW.query.query,
- titleSectionProps: partial({
- name: 'New SQL query',
- }),
sourceQuery: partial({
display: ChartDisplayType.ActionsBar,
}),
})
+ expect(editorRootLogic.values.titleSectionProps).toMatchObject({
+ name: 'New SQL query',
+ })
expect(window.location.hash).not.toContain('view')
expect(window.location.search).not.toContain('open_view')
})
@@ -615,6 +632,8 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
logic.actions.createTab('SELECT 1')
await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
@@ -637,6 +656,8 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
router.actions.push(urls.sqlEditor(), { open_insight: MOCK_DATA_TABLE_INSIGHT_SHORT_ID })
@@ -656,7 +677,7 @@ describe('sqlEditorLogic', () => {
})
// The button should not appear "dirty" immediately after load
- expect(logic.values.updateInsightButtonEnabled).toEqual(false)
+ expect(editorRootLogic.values.updateInsightButtonEnabled).toEqual(false)
})
it('does not dispatch syncUrlWithQuery before the API responds', async () => {
@@ -737,6 +758,8 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
logic.actions.createTab('SELECT 1')
await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
@@ -775,11 +798,11 @@ describe('sqlEditorLogic', () => {
id: 'created-view-id',
name: 'Created view',
}),
- titleSectionProps: partial({
- name: 'Created view',
- }),
})
+ expect(editorRootLogic.values.titleSectionProps).toMatchObject({
+ name: 'Created view',
+ })
await new Promise((resolve) => setTimeout(resolve, 0))
expect(router.values.hashParams.view).toEqual('created-view-id')
@@ -896,12 +919,14 @@ describe('sqlEditorLogic', () => {
editor: createMockEditor(),
})
logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
router.actions.push(urls.sqlEditor(), { source: 'endpoint' })
await expectLogic(logic).toDispatchActions(['setEditorSource', 'createTab', 'updateTab'])
- expect(logic.values.titleSectionProps.forceBackTo).toEqual({
+ expect(editorRootLogic.values.titleSectionProps.forceBackTo).toEqual({
key: 'endpoints',
name: 'Endpoints',
path: urls.endpoints(),
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index c79d85dd50ca..126ccf980e54 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -31,14 +31,12 @@ import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'
import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'
import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'
-import { objectsEqual, removeUndefinedAndNull, slugify } from 'lib/utils'
-import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { objectsEqual, slugify } from 'lib/utils'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { parseQueryTablesAndColumns, queryUsesFiltersPlaceholder } from 'scenes/data-warehouse/editor/sql-utils'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightsApi } from 'scenes/insights/utils/api'
-import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -51,7 +49,6 @@ import {
DataTableNode,
DataVisualizationNode,
DatabaseSchemaViewTable,
- FileSystemIconType,
HogLanguage,
HogQLFilters,
HogQLMetadata,
@@ -60,7 +57,6 @@ import {
NodeKind,
} from '~/queries/schema/schema-general'
import {
- Breadcrumb,
ChartDisplayType,
DataWarehouseSavedQuery,
DataWarehouseSavedQueryDraft,
@@ -78,7 +74,6 @@ import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogi
import { validateSavedQueryName } from '../saved_queries/savedQueryNameValidation'
import { dataModelingLogic } from '../scene/dataModelingLogic'
import { draftsLogic } from './draftsLogic'
-import { editorSceneLogic } from './editorSceneLogic'
import { fixSQLErrorsLogic } from './fixSQLErrorsLogic'
import { findInnermostSelectAtOffset, findQueryAtCursor, type QueryRange, splitQueries } from './multiQueryUtils'
import { OutputTab, outputPaneLogic } from './outputPaneLogic'
@@ -181,12 +176,6 @@ export interface QueryTab {
export type SqlEditorSource = 'insight' | 'endpoint'
-export interface SaveAsMenuItem {
- action: 'insight' | 'endpoint' | 'view'
- label: string
- dataAttr?: string
-}
-
export interface SuggestionPayload {
suggestedValue?: string
originalValue?: string
@@ -224,7 +213,7 @@ function hasOwnProperty(object: Record<string, any>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(object, key)
}
-function normalizeFiltersForUrl(filters: HogQLFilters | null | undefined): HogQLFilters | undefined {
+export function normalizeFiltersForUrl(filters: HogQLFilters | null | undefined): HogQLFilters | undefined {
const normalizedFilters: HogQLFilters = {}
if (filters?.properties?.length) {
@@ -250,18 +239,7 @@ function parseFiltersFromUrl(filters: unknown): HogQLFilters | undefined {
return normalizeFiltersForUrl(filters as HogQLFilters)
}
-function setFiltersHashParam(url: URL, filters: HogQLFilters | null | undefined): void {
- const normalizedFilters = normalizeFiltersForUrl(filters)
- if (!normalizedFilters) {
- return
- }
-
- const hashParams = new URLSearchParams(url.hash ? url.hash.slice(1) : '')
- hashParams.set('filters', JSON.stringify(normalizedFilters))
- url.hash = hashParams.toString()
-}
-
-function normalizeRawQuerySource(source: HogQLQuery): HogQLQuery {
+export function normalizeRawQuerySource(source: HogQLQuery): HogQLQuery {
return {
...source,
sendRawQuery: source.connectionId ? source.sendRawQuery || undefined : undefined,
@@ -277,7 +255,7 @@ function sanitizeSourceQuery(sourceQuery: DataVisualizationNode): DataVisualizat
}
}
-function toDataVisualizationNode(
+export function toDataVisualizationNode(
query: QueryBasedInsightModel['query'] | null | undefined
): DataVisualizationNode | undefined {
if (!query) {
@@ -300,7 +278,7 @@ function toDataVisualizationNode(
return undefined
}
-function getCurrentVisualizationQuery(
+export function getCurrentVisualizationQuery(
dataLogicKey: string,
fallbackQuery: DataVisualizationNode
): DataVisualizationNode {
@@ -424,8 +402,6 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
],
outputPaneLogic({ tabId: props.tabId }),
['setActiveTab'],
- editorSceneLogic,
- ['reportAIQueryPrompted', 'reportAIQueryAccepted', 'reportAIQueryRejected', 'reportAIQueryPromptOpen'],
fixSQLErrorsLogic,
['fixErrors', 'fixErrorsSuccess', 'fixErrorsFailure'],
draftsLogic,
@@ -534,14 +510,15 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
shouldRunQuery,
}),
onRejectSuggestedQueryInput: true,
- shareTab: true,
- openHistoryModal: true,
- closeHistoryModal: true,
+ reportAIQueryPrompted: true,
+ reportAIQueryAccepted: true,
+ reportAIQueryRejected: true,
+ reportAIQueryPromptOpen: true,
setInProgressViewEdit: (viewId: string, historyId: string) => ({
viewId,
historyId,
}),
- setInProgressViewEdits: (inProgressViewEdits: Record<DataWarehouseSavedQuery['id'], string>) => ({
+ setInProgressViewEdits: (inProgressViewEdits: Record<string, string>) => ({
inProgressViewEdits,
}),
deleteInProgressViewEdit: (viewId: string) => ({ viewId }),
@@ -549,7 +526,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
draftId,
historyId,
}),
- setInProgressDraftEdits: (inProgressDraftEdits: Record<DataWarehouseSavedQueryDraft['id'], string>) => ({
+ setInProgressDraftEdits: (inProgressDraftEdits: Record<string, string>) => ({
inProgressDraftEdits,
}),
deleteInProgressDraftEdit: (draftId: string) => ({ draftId }),
@@ -775,16 +752,9 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
_setSuggestionPayload: (_, { payload }) => payload,
},
],
- isHistoryModalOpen: [
- false as boolean,
- {
- openHistoryModal: () => true,
- closeHistoryModal: () => false,
- },
- ],
// if a view edit starts, store the historyId in the state
inProgressViewEdits: [
- {} as Record<DataWarehouseSavedQuery['id'], string>,
+ {} as Record<string, string>,
{
setInProgressViewEdit: (state, { viewId, historyId }) => ({
...state,
@@ -799,7 +769,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
},
],
inProgressDraftEdits: [
- {} as Record<DataWarehouseSavedQueryDraft['id'], string>,
+ {} as Record<string, string>,
{
setInProgressDraftEdit: (state, { draftId, historyId }) => ({
...state,
@@ -867,6 +837,18 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
fixErrorsFailure: () => {
posthog.capture('ai-error-fixer-failure')
},
+ reportAIQueryPrompted: () => {
+ posthog.capture('ai_query_prompted')
+ },
+ reportAIQueryAccepted: () => {
+ posthog.capture('ai_query_accepted')
+ },
+ reportAIQueryRejected: () => {
+ posthog.capture('ai_query_rejected')
+ },
+ reportAIQueryPromptOpen: () => {
+ posthog.capture('ai_query_prompt_open')
+ },
insertTextAtCursor: ({ text }) => {
const editor = props.editor
if (!editor) {
@@ -898,46 +880,6 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
editor.focus()
},
- shareTab: () => {
- const currentTab = values.activeTab
- if (!currentTab) {
- return
- }
-
- if (currentTab.insight) {
- const currentUrl = new URL(window.location.href)
- const shareUrl = new URL(currentUrl.origin + currentUrl.pathname)
- shareUrl.searchParams.set('open_insight', currentTab.insight.short_id)
-
- if (currentTab.insight.query?.kind === NodeKind.DataVisualizationNode) {
- const query = (currentTab.insight.query as DataVisualizationNode).source.query
- if (values.queryInput !== query) {
- shareUrl.searchParams.set('open_query', values.queryInput ?? '')
- }
- }
- setFiltersHashParam(shareUrl, values.sourceQuery.source.filters)
-
- void copyToClipboard(shareUrl.toString(), 'share link')
- } else if (currentTab.view) {
- const currentUrl = new URL(window.location.href)
- const shareUrl = new URL(currentUrl.origin + currentUrl.pathname)
- shareUrl.searchParams.set('open_view', currentTab.view.id)
-
- if (values.queryInput != currentTab.view.query?.query) {
- shareUrl.searchParams.set('open_query', values.queryInput ?? '')
- }
- setFiltersHashParam(shareUrl, values.sourceQuery.source.filters)
-
- void copyToClipboard(shareUrl.toString(), 'share link')
- } else {
- const currentUrl = new URL(window.location.href)
- const shareUrl = new URL(currentUrl.origin + currentUrl.pathname)
- shareUrl.searchParams.set('open_query', values.queryInput ?? '')
- setFiltersHashParam(shareUrl, values.sourceQuery.source.filters)
-
- void copyToClipboard(shareUrl.toString(), 'share link')
- }
- },
setSuggestedQueryInput: ({ suggestedQueryInput, source }) => {
// If there's no active tab, create one first to ensure Monaco Editor is available
if (!values.activeTab) {
@@ -2143,26 +2085,6 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
return splitRanges.some((q) => q.query.trim() === lastRunQueryText)
},
],
- updateInsightButtonEnabled: [
- (s) => [s.sourceQuery, s.activeTab, s.editingInsight, s.dataLogicKey],
- (sourceQuery, activeTab, editingInsight, dataLogicKey) => {
- if (!editingInsight?.query) {
- return false
- }
-
- const updatedName = activeTab?.name !== editingInsight.name
- const currentVisualizationQuery = getCurrentVisualizationQuery(dataLogicKey, sourceQuery)
-
- const sourceQueryWithoutUndefinedAndNullKeys = removeUndefinedAndNull(currentVisualizationQuery)
- // Normalize so DataTableNode-based insights don't look "changed" immediately after load.
- const editingInsightQuery = toDataVisualizationNode(editingInsight.query) ?? editingInsight.query
-
- return (
- updatedName ||
- !equal(sourceQueryWithoutUndefinedAndNullKeys, removeUndefinedAndNull(editingInsightQuery))
- )
- },
- ],
hasFiltersPlaceholder: [
(s) => [s.queryInput],
(queryInput) => {
@@ -2177,194 +2099,6 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
dataLogicKey: [(_, p) => [p.tabId], (tabId) => `data-warehouse-editor-data-node-${tabId}`],
isDraft: [(s) => [s.activeTab], (activeTab) => (activeTab ? !!activeTab.draft?.id : false)],
currentDraft: [(s) => [s.activeTab], (activeTab) => (activeTab ? activeTab.draft : null)],
- breadcrumbs: [
- (s) => [s.activeTab],
- (activeTab): Breadcrumb[] => {
- const { draft, insight, view } = activeTab || {}
- const first = {
- key: Scene.SQLEditor,
- name: 'SQL query',
- to: urls.sqlEditor(),
- iconType: 'sql_editor' as FileSystemIconType,
- }
- if (view) {
- return [
- {
- key: view.id,
- name: view.name,
- path: urls.sqlEditor({ view_id: view.id }),
- iconType: 'sql_editor',
- },
- ]
- } else if (insight) {
- return [
- first,
- {
- key: insight.id,
- name: insight.name || insight.derived_name || 'Untitled',
- path: urls.sqlEditor({
- insightShortId: insight.short_id,
- }),
- iconType: 'sql_editor',
- },
- ]
- } else if (draft) {
- return [
- first,
- {
- key: draft.id,
- name: draft.name || 'Untitled',
- path: urls.sqlEditor({ draftId: draft.id }),
- iconType: 'sql_editor',
- },
- ]
- }
- return [first]
- },
- ],
- titleSectionProps: [
- (s) => [
- s.editingInsight,
- s.insightLoading,
- s.editingView,
- s.viewLoading,
- s.editorSource,
- s.dashboardId,
- s.activeTab,
- ],
- (editingInsight, insightLoading, editingView, viewLoading, editorSource, dashboardId, activeTab) => {
- if (editingInsight) {
- const forceBackTo: Breadcrumb = dashboardId
- ? {
- key: 'dashboard',
- name: 'Back to dashboard',
- path: urls.dashboard(dashboardId),
- iconType: 'dashboard',
- }
- : {
- key: editingInsight.short_id,
- name: 'Back to insight',
- path: urls.insightView(editingInsight.short_id),
- iconType: 'insight/hog',
- }
-
- return {
- forceBackTo,
- name: editingInsight.name || editingInsight.derived_name || 'Untitled',
- resourceType: { type: 'insight/hog' },
- }
- }
-
- if (insightLoading) {
- return {
- name: 'Loading insight...',
- resourceType: { type: 'insight/hog' },
- }
- }
-
- if (editingView) {
- return {
- name: editingView.name,
- resourceType: {
- type: editingView.is_materialized ? 'matview' : 'view',
- },
- }
- }
-
- if (viewLoading) {
- return {
- name: 'Loading view...',
- resourceType: { type: 'view' },
- }
- }
-
- if (!activeTab) {
- const searchParams = new URLSearchParams(window.location.search)
- const hashParams = new URLSearchParams(window.location.hash.slice(1))
- if (searchParams.get('open_view') || hashParams.get('view')) {
- return {
- name: 'Loading view...',
- resourceType: { type: 'view' },
- }
- }
-
- if (searchParams.get('open_insight') || hashParams.get('insight')) {
- return {
- name: 'Loading insight...',
- resourceType: { type: 'insight/hog' },
- }
- }
- }
-
- if (editorSource === 'endpoint') {
- const forceBackTo: Breadcrumb = {
- key: 'endpoints',
- name: 'Endpoints',
- path: urls.endpoints(),
- iconType: 'endpoints',
- }
-
- return {
- forceBackTo,
- name: 'New endpoint',
- resourceType: { type: 'sql_editor' },
- }
- }
-
- if (dashboardId) {
- const forceBackTo: Breadcrumb = {
- key: 'dashboard',
- name: 'Back to dashboard',
- path: urls.dashboard(dashboardId),
- iconType: 'dashboard',
- }
-
- return {
- forceBackTo,
- name: 'New SQL query',
- resourceType: { type: 'sql_editor' },
- }
- }
-
- return {
- name: 'New SQL query',
- resourceType: { type: 'sql_editor' },
- }
- },
- ],
-
- saveAsMenuItems: [
- (s) => [s.editorSource, s.dashboardId, s.featureFlags],
- (editorSource, dashboardId, featureFlags): { primary: SaveAsMenuItem; secondary: SaveAsMenuItem[] } => {
- const endpointsEnabled = !!featureFlags[FEATURE_FLAGS.ENDPOINTS]
- const saveAsInsightItem: SaveAsMenuItem = {
- action: 'insight',
- label: dashboardId ? 'Save & add to dashboard' : 'Save as insight',
- }
- const saveAsEndpointItem: SaveAsMenuItem = {
- action: 'endpoint',
- label: 'Save as endpoint',
- }
- const saveAsViewItem: SaveAsMenuItem = {
- action: 'view',
- label: 'Save as view',
- dataAttr: 'sql-editor-save-view-button',
- }
-
- if (editorSource === 'endpoint' && endpointsEnabled) {
- return {
- primary: saveAsEndpointItem,
- secondary: [saveAsInsightItem, saveAsViewItem],
- }
- }
-
- return {
- primary: saveAsInsightItem,
- secondary: endpointsEnabled ? [saveAsEndpointItem, saveAsViewItem] : [saveAsViewItem],
- }
- },
- ],
-
selectedQueryColumns: [
(s) => [s.selectedQueryTablesAndColumns],
(tablesAndColumns: Record<string, Record<string, boolean>>): Record<string, boolean> => {
@@ -2908,6 +2642,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
cache.queryOutlineRange = null
cache.updateQueryOutline = null
cache.umountDataNode?.()
+ cache.umountDataNode = null
// Drop any pending decoration work so late callbacks don't touch a disposed editor.
if (cache.activeQueryDecorationDebounceTimeout) {