Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feature: add explain with AI in query performance (#41415)

Ali Waseemec20b7e3262d
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
index 6234374fc98..d987ace5e36 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
@@ -2,19 +2,33 @@ import { Lightbulb, ChevronsUpDown } from 'lucide-react'
import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
+import { useFlag } from 'common'
import { formatSql } from 'lib/formatSql'
-import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, cn } from 'ui'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ cn,
+ AiIconAnimation,
+} from 'ui'
+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'
import { QueryPanelContainer, QueryPanelSection } from './QueryPanel'
import {
QUERY_PERFORMANCE_COLUMNS,
QUERY_PERFORMANCE_REPORT_TYPES,
} from './QueryPerformance.constants'
+import { QueryPerformanceRow } from './QueryPerformance.types'
+import { buildQueryExplanationPrompt } from './QueryPerformance.ai'
import { formatDuration } from './QueryPerformance.utils'
+import { useTrack } from 'lib/telemetry/track'
interface QueryDetailProps {
- reportType: QUERY_PERFORMANCE_REPORT_TYPES
- selectedRow: any
+ selectedRow?: QueryPerformanceRow
onClickViewSuggestion: () => void
+ onClose?: () => void
}
// Load SqlMonacoBlock (monaco editor) client-side only (does not behave well server-side)
@@ -25,12 +39,18 @@ const SqlMonacoBlock = dynamic(
}
)
-export const QueryDetail = ({ selectedRow, onClickViewSuggestion }: QueryDetailProps) => {
+export const QueryDetail = ({ selectedRow, onClickViewSuggestion, onClose }: QueryDetailProps) => {
// [Joshen] TODO implement this logic once the linter rules are in
const isLinterWarning = false
const report = QUERY_PERFORMANCE_COLUMNS
const [query, setQuery] = useState(selectedRow?.['query'])
+ const { openSidebar } = useSidebarManagerSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
+ const track = useTrack()
+
+ const showExplainWithAiInQueryPerformance = useFlag('ShowExplainWithAiInQueryPerformance')
+
useEffect(() => {
if (selectedRow !== undefined) {
const formattedQuery = formatSql(selectedRow['query'])
@@ -40,10 +60,44 @@ export const QueryDetail = ({ selectedRow, onClickViewSuggestion }: QueryDetailP
const [isExpanded, setIsExpanded] = useState(false)
+ const handleExplainQuery = () => {
+ if (!selectedRow?.query) return
+
+ const { query, prompt } = buildQueryExplanationPrompt(selectedRow)
+
+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
+ aiSnap.newChat({
+ sqlSnippets: [
+ {
+ label: 'Query',
+ content: query,
+ },
+ ],
+ initialMessage: prompt,
+ })
+
+ track('query_performance_explain_with_ai_button_clicked')
+
+ // Close the query detail panel since we need to see the AI assistant panel
+ onClose?.()
+ }
+
return (
<QueryPanelContainer>
<QueryPanelSection className="pt-2 border-b relative">
- <h4 className="mb-4">Query pattern</h4>
+ <div className="flex items-center justify-between mb-4">
+ <h4>Query pattern</h4>
+ {showExplainWithAiInQueryPerformance && (
+ <Button
+ type="default"
+ size="tiny"
+ icon={<AiIconAnimation size={14} />}
+ onClick={handleExplainQuery}
+ >
+ Explain with AI
+ </Button>
+ )}
+ </div>
<div
className={cn(
'overflow-hidden pb-0 z-0 relative transition-all duration-300',
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts
new file mode 100644
index 00000000000..1a20f2981c9
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts
@@ -0,0 +1,49 @@
+import { QueryPerformanceRow } from './QueryPerformance.types'
+
+export interface QueryExplanationPrompt {
+ query: string
+ prompt: string
+}
+
+export function buildQueryExplanationPrompt(
+ selectedRow: QueryPerformanceRow
+): QueryExplanationPrompt {
+ const metadata = [
+ `Total Time: ${selectedRow.total_time.toLocaleString()}`,
+ `Calls: ${selectedRow.calls.toLocaleString()}`,
+ `Mean Time: ${selectedRow.mean_time.toLocaleString()}`,
+ `Max Time: ${selectedRow.max_time.toLocaleString()}`,
+ `Min Time: ${selectedRow.min_time.toLocaleString()}`,
+ `Rows Read: ${selectedRow.rows_read.toLocaleString()}`,
+ `Cache Hit Rate: ${selectedRow.cache_hit_rate.toLocaleString()}%`,
+ `Role: ${selectedRow.rolname}`,
+ ].join('\n')
+
+ let additionalContext = ''
+ if (selectedRow.index_advisor_result) {
+ const indexResult = selectedRow.index_advisor_result
+
+ if (indexResult.index_statements.length > 0) {
+ additionalContext = `\n\nIndex Advisor Recommendations:\n${indexResult.index_statements.join('\n')}\n\nCost Analysis:\n- Startup Cost Before: ${indexResult.startup_cost_before}\n- Startup Cost After: ${indexResult.startup_cost_after}\n- Total Cost Before: ${indexResult.total_cost_before}\n- Total Cost After: ${indexResult.total_cost_after}`
+ }
+ }
+
+ const prompt = `Analyze this database query and provide a brief, concise explanation:
+
+**Performance Metrics:**
+${metadata}
+
+${additionalContext}
+
+Provide a short response covering:
+1. What the query does (1-2 sentences)
+2. Performance assessment (good/concerning and why, keep it brief 2-3 sentences)
+3. Actionable optimization suggestions (if any, keep it brief 2-3 sentences)
+
+Keep your response concise and focused on actionable insights. We can continue the conversation if needed to get more details.`
+
+ return {
+ query: selectedRow.query,
+ prompt,
+ }
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
index 922ced2920b..4dbeada04b8 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
@@ -618,9 +618,9 @@ export const QueryPerformanceGrid = ({
<TabsContent_Shadcn_ value="details" className="mt-0 flex-grow min-h-0 overflow-y-auto">
{selectedRow !== undefined && (
<QueryDetail
- reportType={reportType}
selectedRow={reportData[selectedRow]}
onClickViewSuggestion={() => setView('suggestion')}
+ onClose={() => setSelectedRow(undefined)}
/>
)}
</TabsContent_Shadcn_>
diff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.ts
index b7bbe87a256..3a41d04f115 100644
--- a/packages/common/telemetry-constants.ts
+++ b/packages/common/telemetry-constants.ts
@@ -2549,6 +2549,18 @@ export interface AdvisorAssistantButtonClickedEvent {
groups: TelemetryGroups
}
+/**
+ * User clicked on "Explain with AI" button in Query Performance detail panel
+ *
+ * @group Events
+ * @source studio
+ * @page /dashboard/project/{ref}/observability/query-performance
+ */
+export interface QueryPerformanceAIExplanationButtonClickedEvent {
+ action: 'query_performance_explain_with_ai_button_clicked'
+ groups: TelemetryGroups
+}
+
/**
* User opened the request upgrade modal (for users without billing permissions).
*
@@ -2731,5 +2743,6 @@ export type TelemetryEvent =
| LogDrainConfirmButtonSubmittedEvent
| AdvisorDetailOpenedEvent
| AdvisorAssistantButtonClickedEvent
+ | QueryPerformanceAIExplanationButtonClickedEvent
| RequestUpgradeModalOpenedEvent
| RequestUpgradeSubmittedEvent