Skip to content

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

Feat/index suggestions inline (#35107)

Jonathan Summers-Muir2815dac7e097
diff --git a/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx b/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx
index 4b922043dba..0dcef19d54b 100644
--- a/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx
+++ b/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx
@@ -1,4 +1,3 @@
-import { useQueryClient } from '@tanstack/react-query'
import { Check, ChevronsUpDown, Loader2 } from 'lucide-react'
import Link from 'next/link'
import { Fragment, useEffect, useMemo, useState } from 'react'
@@ -6,12 +5,13 @@ import { toast } from 'sonner'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import CodeEditor from 'components/ui/CodeEditor/CodeEditor'
+import { DocsButton } from 'components/ui/DocsButton'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { databaseKeys } from 'data/database/keys'
+import { useDatabaseIndexCreateMutation } from 'data/database-indexes/index-create-mutation'
import { useSchemasQuery } from 'data/database/schemas-query'
import { useTableColumnsQuery } from 'data/database/table-columns-query'
import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'
-import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
+import { useIsOrioleDb } from 'hooks/misc/useSelectedProject'
import {
Button,
CommandEmpty_Shadcn_,
@@ -33,13 +33,11 @@ import {
SidePanel,
cn,
} from 'ui'
+import { Admonition } from 'ui-patterns'
import { MultiSelectOption } from 'ui-patterns/MultiSelectDeprecated'
import { MultiSelectV2 } from 'ui-patterns/MultiSelectDeprecated/MultiSelectV2'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { INDEX_TYPES } from './Indexes.constants'
-import { useIsOrioleDb } from 'hooks/misc/useSelectedProject'
-import { Admonition } from 'ui-patterns'
-import { DocsButton } from 'components/ui/DocsButton'
interface CreateIndexSidePanelProps {
visible: boolean
@@ -47,7 +45,6 @@ interface CreateIndexSidePanelProps {
}
const CreateIndexSidePanel = ({ visible, onClose }: CreateIndexSidePanelProps) => {
- const queryClient = useQueryClient()
const { project } = useProjectContext()
const isOrioleDb = useIsOrioleDb()
@@ -81,15 +78,11 @@ const CreateIndexSidePanel = ({ visible, onClose }: CreateIndexSidePanelProps) =
connectionString: project?.connectionString,
})
- const { mutate: execute, isLoading: isExecuting } = useExecuteSqlMutation({
- onSuccess: async () => {
- await queryClient.invalidateQueries(databaseKeys.indexes(project?.ref, selectedSchema))
+ const { mutate: createIndex, isLoading: isExecuting } = useDatabaseIndexCreateMutation({
+ onSuccess: () => {
onClose()
toast.success(`Successfully created index`)
},
- onError: (error) => {
- toast.error(`Failed to create index: ${error.message}`)
- },
})
const entityTypes = useMemo(
@@ -119,11 +112,17 @@ CREATE INDEX ON "${selectedSchema}"."${selectedEntity}" USING ${selectedIndexTyp
const onSaveIndex = () => {
if (!project) return console.error('Project is required')
+ if (!selectedEntity) return console.error('Entity is required')
- execute({
+ createIndex({
projectRef: project.ref,
connectionString: project.connectionString,
- sql: generatedSQL,
+ payload: {
+ schema: selectedSchema,
+ entity: selectedEntity,
+ type: selectedIndexType,
+ columns: selectedColumns,
+ },
})
}
diff --git a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
index 74252769dc9..3eee09b8556 100644
--- a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
+++ b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
@@ -1,4 +1,5 @@
import { partition, sortBy } from 'lodash'
+import { AlertCircle, Search, Trash } from 'lucide-react'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
@@ -9,12 +10,11 @@ import AlertError from 'components/ui/AlertError'
import CodeEditor from 'components/ui/CodeEditor/CodeEditor'
import SchemaSelector from 'components/ui/SchemaSelector'
import ShimmeringLoader, { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
-import { DatabaseIndex, useIndexesQuery } from 'data/database/indexes-query'
+import { useDatabaseIndexDeleteMutation } from 'data/database-indexes/index-delete-mutation'
+import { DatabaseIndex, useIndexesQuery } from 'data/database-indexes/indexes-query'
import { useSchemasQuery } from 'data/database/schemas-query'
-import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { PROTECTED_SCHEMAS } from 'lib/constants/schemas'
-import { AlertCircle, Search, Trash } from 'lucide-react'
import { Button, Input, SidePanel } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import ProtectedSchemaWarning from '../ProtectedSchemaWarning'
@@ -32,7 +32,6 @@ const Indexes = () => {
const {
data: allIndexes,
- refetch: refetchIndexes,
error: indexesError,
isLoading: isLoadingIndexes,
isSuccess: isSuccessIndexes,
@@ -52,15 +51,11 @@ const Indexes = () => {
connectionString: project?.connectionString,
})
- const { mutate: execute, isLoading: isExecuting } = useExecuteSqlMutation({
+ const { mutate: deleteIndex, isLoading: isExecuting } = useDatabaseIndexDeleteMutation({
onSuccess: async () => {
- await refetchIndexes()
setSelectedIndexToDelete(undefined)
toast.success('Successfully deleted index')
},
- onError: (error) => {
- toast.error(`Failed to delete index: ${error.message}`)
- },
})
const [protectedSchemas] = partition(schemas ?? [], (schema) =>
@@ -77,10 +72,11 @@ const Indexes = () => {
const onConfirmDeleteIndex = (index: DatabaseIndex) => {
if (!project) return console.error('Project is required')
- execute({
+
+ deleteIndex({
projectRef: project.ref,
connectionString: project.connectionString,
- sql: `drop index if exists "${index.name}"`,
+ name: index.name,
})
}
diff --git a/apps/studio/components/interfaces/QueryPerformance/EnableIndexAdvisorButton.tsx b/apps/studio/components/interfaces/QueryPerformance/EnableIndexAdvisorButton.tsx
new file mode 100644
index 00000000000..d78b6c9598e
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/EnableIndexAdvisorButton.tsx
@@ -0,0 +1,124 @@
+import { useState } from 'react'
+import { toast } from 'sonner'
+
+import { useIsIndexAdvisorAvailable } from 'components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorAvailable'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDatabaseExtensionEnableMutation } from 'data/database-extensions/database-extension-enable-mutation'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+ Badge,
+ Button,
+ InfoIcon,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import { getIndexAdvisorExtensions } from './index-advisor.utils'
+
+export const EnableIndexAdvisorButton = () => {
+ const { project } = useProjectContext()
+ const isAdvisorAvailable = useIsIndexAdvisorAvailable()
+ const [isDialogOpen, setIsDialogOpen] = useState(false)
+
+ const { data: extensions } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+ const { hypopg, indexAdvisor } = getIndexAdvisorExtensions(extensions)
+
+ const { mutateAsync: enableExtension, isLoading: isEnablingExtension } =
+ useDatabaseExtensionEnableMutation()
+
+ const onEnableIndexAdvisor = async () => {
+ if (project === undefined) return toast.error('Project is required')
+
+ try {
+ // Enable hypopg extension if not already installed
+ if (hypopg?.installed_version === null) {
+ await enableExtension({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ name: hypopg.name,
+ schema: hypopg?.schema ?? 'extensions',
+ version: hypopg.default_version,
+ })
+ }
+
+ // Enable index_advisor extension if not already installed
+ if (indexAdvisor?.installed_version === null) {
+ await enableExtension({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ name: indexAdvisor.name,
+ schema: indexAdvisor?.schema ?? 'extensions',
+ version: indexAdvisor.default_version,
+ })
+ }
+ toast.success('Successfully enabled Index Advisor!')
+ setIsDialogOpen(false)
+ } catch (error: any) {
+ toast.error(`Failed to enable Index Advisor: ${error.message}`)
+ }
+ }
+
+ if (isAdvisorAvailable) return null
+
+ return (
+ <AlertDialog open={isDialogOpen} onOpenChange={() => setIsDialogOpen(!isDialogOpen)}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <AlertDialogTrigger asChild>
+ <Button type="outline" className={`rounded-full`} icon={<InfoIcon />}>
+ Enable Index Advisor
+ </Button>
+ </AlertDialogTrigger>
+ </TooltipTrigger>
+ <TooltipContent side="top">Recommends indexes to improve query performance</TooltipContent>
+ </Tooltip>
+
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Enable Index Advisor</AlertDialogTitle>
+ <AlertDialogDescription>
+ Index Advisor is a tool that helps you identify and simulate indexes that can improve
+ query performance. To use Index Advisor, you need to enable the following Postgres
+ extensions:
+ <ul className="list-disc pl-6 py-4 flex flex-col gap-2">
+ <li>
+ <Badge className="font-mono text-foreground">index_advisor</Badge> - Recommends
+ database indexes
+ </li>
+ <li>
+ <Badge className="font-mono text-foreground">hypopg</Badge> - For hypothetical
+ indexes simulation
+ </li>
+ </ul>
+ These extensions help identify and simulate indexes that can improve query performance
+ without having to create actual indexes.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={(e) => {
+ e.preventDefault()
+ onEnableIndexAdvisor()
+ }}
+ disabled={isEnablingExtension}
+ >
+ {isEnablingExtension ? 'Enabling...' : 'Enable Extensions'}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/IndexAdvisorDisabledState.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisorDisabledState.tsx
index deffaf61c07..62f3955956e 100644
--- a/apps/studio/components/interfaces/QueryPerformance/IndexAdvisorDisabledState.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisorDisabledState.tsx
@@ -6,6 +6,7 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConte
import { DocsButton } from 'components/ui/DocsButton'
import { useDatabaseExtensionEnableMutation } from 'data/database-extensions/database-extension-enable-mutation'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { getIndexAdvisorExtensions } from './index-advisor.utils'
import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'
import { Markdown } from '../Markdown'
@@ -16,8 +17,7 @@ export const IndexAdvisorDisabledState = () => {
projectRef: project?.ref,
connectionString: project?.connectionString,
})
- const hypopgExtension = (extensions ?? []).find((ext) => ext.name === 'hypopg')
- const indexAdvisorExtension = (extensions ?? []).find((ext) => ext.name === 'index_advisor')
+ const { hypopg, indexAdvisor } = getIndexAdvisorExtensions(extensions)
const { mutateAsync: enableExtension, isLoading: isEnablingExtension } =
useDatabaseExtensionEnableMutation()
@@ -26,22 +26,22 @@ export const IndexAdvisorDisabledState = () => {
if (project === undefined) return console.error('Project is required')
try {
- if (hypopgExtension?.installed_version === null) {
+ if (hypopg?.installed_version === null) {
await enableExtension({
projectRef: project?.ref,
connectionString: project?.connectionString,
- name: hypopgExtension.name,
- schema: hypopgExtension?.schema ?? 'extensions',
- version: hypopgExtension.default_version,
+ name: hypopg.name,
+ schema: hypopg?.schema ?? 'extensions',
+ version: hypopg.default_version,
})
}
- if (indexAdvisorExtension?.installed_version === null) {
+ if (indexAdvisor?.installed_version === null) {
await enableExtension({
projectRef: project?.ref,
connectionString: project?.connectionString,
- name: indexAdvisorExtension.name,
- schema: indexAdvisorExtension?.schema ?? 'extensions',
- version: indexAdvisorExtension.default_version,
+ name: indexAdvisor.name,
+ schema: indexAdvisor?.schema ?? 'extensions',
+ version: indexAdvisor.default_version,
})
}
toast.success('Successfully enabled index advisor!')
@@ -56,7 +56,7 @@ export const IndexAdvisorDisabledState = () => {
<Markdown
className="text-foreground"
content={
- indexAdvisorExtension === undefined
+ indexAdvisor === undefined
? 'Newer version of Postgres required'
: 'Postgres extensions `index_advisor` and `hypopg` required'
}
@@ -65,7 +65,7 @@ export const IndexAdvisorDisabledState = () => {
<AlertDescription_Shadcn_>
<Markdown
content={
- indexAdvisorExtension === undefined
+ indexAdvisor === undefined
? 'Upgrade to the latest version of Postgres to get recommendations on indexes for your queries'
: 'These extensions can help in recommending database indexes to reduce the costs of your query.'
}
@@ -74,7 +74,7 @@ export const IndexAdvisorDisabledState = () => {
<AlertDescription_Shadcn_ className="mt-3">
<div className="flex items-center gap-x-2">
- {indexAdvisorExtension === undefined ? (
+ {indexAdvisor === undefined ? (
<Button asChild type="default">
<Link href={`/project/${ref}/settings/infrastructure`}>Upgrade Postgres version</Link>
</Button>
diff --git a/apps/studio/components/interfaces/QueryPerformance/IndexImprovementText.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexImprovementText.tsx
new file mode 100644
index 00000000000..23472e38ab2
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/IndexImprovementText.tsx
@@ -0,0 +1,28 @@
+import { HTMLAttributes } from 'react'
+
+import { cn } from 'ui'
+import { calculateImprovement } from './index-advisor.utils'
+
+interface IndexImprovementTextProps extends HTMLAttributes<HTMLParagraphElement> {
+ indexStatements: string[]
+ totalCostBefore: number
+ totalCostAfter: number
+}
+
+export const IndexImprovementText = ({
+ indexStatements,
+ totalCostBefore,
+ totalCostAfter,
+ className,
+ ...props
+}: IndexImprovementTextProps) => {
+ const improvement = calculateImprovement(totalCostBefore, totalCostAfter)
+
+ return (
+ <p className={cn('text-sm text-foreground-light', className)} {...props}>
+ Query's performance can be improved by{' '}
+ <span className="text-brand">{improvement.toFixed(2)}%</span> by creating this{' '}
+ {indexStatements.length > 1 ? 'indexes' : 'index'}:
+ </p>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/IndexSuggestionIcon.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexSuggestionIcon.tsx
new file mode 100644
index 00000000000..cf5163492b2
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/IndexSuggestionIcon.tsx
@@ -0,0 +1,146 @@
+import { Loader2 } from 'lucide-react'
+import { MouseEvent, useState } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { GetIndexAdvisorResultResponse } from 'data/database/retrieve-index-advisor-result-query'
+import {
+ Button,
+ cn,
+ CodeBlock,
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+ Separator,
+ WarningIcon,
+} from 'ui'
+import { IndexImprovementText } from './IndexImprovementText'
+import { QueryPanelScoreSection } from './QueryPanel'
+import { useIndexInvalidation } from './hooks/useIndexInvalidation'
+import { createIndexes } from './index-advisor.utils'
+
+interface IndexSuggestionIconProps {
+ indexAdvisorResult: GetIndexAdvisorResultResponse
+ onClickIcon?: () => void
+}
+
+export const IndexSuggestionIcon = ({
+ indexAdvisorResult,
+ onClickIcon,
+}: IndexSuggestionIconProps) => {
+ const { project } = useProjectContext()
+ const [isCreatingIndex, setIsCreatingIndex] = useState(false)
+ const [isHoverCardOpen, setIsHoverCardOpen] = useState(false)
+
+ const invalidateQueries = useIndexInvalidation()
+
+ const handleCreateIndex = async (e: MouseEvent) => {
+ e.stopPropagation()
+
+ setIsCreatingIndex(true)
+
+ try {
+ await createIndexes({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ indexStatements: indexAdvisorResult.index_statements,
+ onSuccess: () => {
+ // Handle UI-specific logic
+ if (onClickIcon) {
+ onClickIcon()
+ setIsHoverCardOpen(false)
+ }
+ },
+ })
+
+ // Only invalidate queries if index creation was successful
+ invalidateQueries()
+ } catch (error) {
+ // Error is already handled by createIndexes with a toast notification
+ // But we could add component-specific error handling here if needed
+ console.error('Failed to create index:', error)
+ setIsCreatingIndex(false)
+ } finally {
+ // Reset the loading state after a short delay to show feedback
+ setTimeout(() => setIsCreatingIndex(false), 1000)
+ }
+ }
+
+ if (!indexAdvisorResult?.index_statements?.length) return null
+
+ return (
+ <HoverCard open={isHoverCardOpen} onOpenChange={setIsHoverCardOpen}>
+ <HoverCardTrigger>
+ <div
+ onClick={(e) => {
+ if (onClickIcon && !isCreatingIndex) {
+ e.stopPropagation()
+ onClickIcon()
+ }
+ }}
+ className="cursor-pointer"
+ >
+ {isCreatingIndex ? (
+ <Loader2 size={16} className="animate-spin text-foreground-light" />
+ ) : (
+ <WarningIcon />
+ )}
+ </div>
+ </HoverCardTrigger>
+ <HoverCardContent className="w-[520px] p-0 overflow-hidden" align="start" alignOffset={-32}>
+ <div className="px-4 py-3 bg-surface-75">
+ <IndexImprovementText
+ indexStatements={indexAdvisorResult.index_statements}
+ totalCostBefore={indexAdvisorResult.total_cost_before}
+ totalCostAfter={indexAdvisorResult.total_cost_after}
+ className="text-sm"
+ />
+ </div>
+ <Separator />
+ <div>
+ <CodeBlock
+ hideLineNumbers
+ value={indexAdvisorResult.index_statements.join(';\n') + ';'}
+ language="sql"
+ className={cn(
+ 'border-none rounded-none',
+ 'max-w-full',
+ '!py-0.5 !px-3.5 prose dark:prose-dark transition',
+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap'
+ )}
+ />
+ </div>
+ <Separator />
+ <QueryPanelScoreSection
+ name="Total cost of query"
+ description="An estimate of how long it will take to return all the rows (Includes start up cost)"
+ before={indexAdvisorResult.total_cost_before}
+ after={indexAdvisorResult.total_cost_after}
+ />
+ <QueryPanelScoreSection
+ hideArrowMarkers
+ className="border-t"
+ name="Start up cost"
+ description="An estimate of how long it will take to fetch the first row"
+ before={indexAdvisorResult.startup_cost_before}
+ after={indexAdvisorResult.startup_cost_after}
+ />
+ <div className="p-3 flex gap-2 items-center border-t justify-end">
+ <Button
+ type="text"
+ onClick={(e) => {
+ e.stopPropagation()
+ if (onClickIcon && !isCreatingIndex) onClickIcon()
+ setIsHoverCardOpen(false)
+ }}
+ disabled={isCreatingIndex}
+ >
+ View details
+ </Button>
+ <Button onClick={handleCreateIndex} loading={isCreatingIndex} disabled={isCreatingIndex}>
+ Create index
+ </Button>
+ </div>
+ </HoverCardContent>
+ </HoverCard>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryCosts.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryCosts.tsx
new file mode 100644
index 00000000000..7c92044d09d
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryCosts.tsx
@@ -0,0 +1,44 @@
+import { cn } from 'ui'
+
+interface QueryCostsProps {
+ currentCost?: number
+ improvedCost?: number
+ improvement?: number
+ className?: string
+}
+
+export const QueryCosts = ({
+ currentCost,
+ improvedCost,
+ improvement,
+ className,
+}: QueryCostsProps) => {
+ if (!currentCost) return null
+
+ return (
+ <div className={cn('flex flex-col gap-y-4', className)}>
+ <h3 className="text-sm">Query costs</h3>
+ <div className="flex flex-col gap-y-2 rounded bg-surface-100 px-4 py-3">
+ <div className="flex items-center justify-between">
+ <p className="text-sm text-foreground-light">Total cost of query</p>
+ <div className="flex flex-col items-end gap-y-1">
+ <div className="flex items-center gap-x-4">
+ <p className="text-sm text-foreground-light">Currently:</p>
+ <p className="font-mono text-sm">{currentCost.toFixed(2)}</p>
+ </div>
+ {improvedCost && (
+ <div className="flex items-center gap-x-4">
+ <p className="text-sm text-foreground-light">With index:</p>
+ <div className="flex items-center gap-x-2">
+ <p className="font-mono text-sm">{improvedCost.toFixed(2)}</p>
+ {improvement && <p className="text-sm text-brand">↓ {improvement.toFixed(1)}%</p>}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ <button className="text-sm text-brand hover:text-brand-600 transition">View more</button>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx
index 0bb768bb475..acb3dd530b7 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx
@@ -1,14 +1,13 @@
import { Check, Lightbulb, Table2 } from 'lucide-react'
import { useState } from 'react'
-import { toast } from 'sonner'
import { AccordionTrigger } from '@ui/components/shadcn/ui/accordion'
+import { useIsIndexAdvisorAvailable } from 'components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorAvailable'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import AlertError from 'components/ui/AlertError'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
import { useGetIndexAdvisorResult } from 'data/database/retrieve-index-advisor-result-query'
import { useGetIndexesFromSelectQuery } from 'data/database/retrieve-index-from-select-query'
-import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
import {
AccordionContent_Shadcn_,
AccordionItem_Shadcn_,
@@ -25,7 +24,10 @@ import {
} from 'ui'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { IndexAdvisorDisabledState } from './IndexAdvisorDisabledState'
+import { IndexImprovementText } from './IndexImprovementText'
import { QueryPanelContainer, QueryPanelScoreSection, QueryPanelSection } from './QueryPanel'
+import { useIndexInvalidation } from './hooks/useIndexInvalidation'
+import { calculateImprovement, createIndexes, hasIndexRecommendations } from './index-advisor.utils'
interface QueryIndexesProps {
selectedRow: any
@@ -39,6 +41,7 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
const isLinterWarning = false
const { project } = useProjectContext()
const [showStartupCosts, setShowStartupCosts] = useState(false)
+ const [isExecuting, setIsExecuting] = useState(false)
const {
data: usedIndexes,
@@ -57,13 +60,7 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
connectionString: project?.connectionString,
})
- const hypopgExtension = (extensions ?? []).find((ext) => ext.name === 'hypopg')
- const indexAdvisorExtension = (extensions ?? []).find((ext) => ext.name === 'index_advisor')
- const isIndexAdvisorAvailable =
- indexAdvisorExtension !== undefined &&
- indexAdvisorExtension.installed_version !== null &&
- hypopgExtension !== undefined &&
- hypopgExtension.installed_version !== null
+ const isAdvisorAvailable = useIsIndexAdvisorAvailable()
const {
data: indexAdvisorResult,
@@ -78,7 +75,7 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
connectionString: project?.connectionString,
query: selectedRow?.['query'],
},
- { enabled: isIndexAdvisorAvailable }
+ { enabled: isAdvisorAvailable }
)
const {
@@ -88,29 +85,37 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
total_cost_after,
total_cost_before,
} = indexAdvisorResult ?? { index_statements: [], total_cost_after: 0, total_cost_before: 0 }
- const hasIndexRecommendation = isSuccessIndexAdvisorResult && index_statements.length > 0
- const totalImprovement = isSuccessIndexAdvisorResult
- ? ((total_cost_before - total_cost_after) / total_cost_before) * 100
- : 0
+ const hasIndexRecommendation = hasIndexRecommendations(
+ indexAdvisorResult,
+ isSuccessIndexAdvisorResult
+ )
+ const totalImprovement = calculateImprovement(total_cost_before, total_cost_after)
- const { mutate: execute, isLoading: isExecuting } = useExecuteSqlMutation({
- onSuccess: async () => {
- await refetch()
- toast.success(`Successfully created index`)
- },
- onError: (error) => {
- toast.error(`Failed to create index: ${error.message}`)
- },
- })
+ const invalidateQueries = useIndexInvalidation()
- const createIndex = () => {
+ const createIndex = async () => {
if (index_statements.length === 0) return
- execute({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- sql: index_statements.join(';\n') + ';',
- })
+ setIsExecuting(true)
+
+ try {
+ await createIndexes({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ indexStatements: index_statements,
+ onSuccess: () => refetch(),
+ })
+
+ // Only invalidate queries if index creation was successful
+ invalidateQueries()
+ } catch (error) {
+ // Error is already handled by createIndexes with a toast notification
+ // But we could add component-specific error handling here if needed
+ console.error('Failed to create index:', error)
+ setIsExecuting(false)
+ } finally {
+ setIsExecuting(false)
+ }
}
return (
@@ -170,7 +175,7 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
<p className="text-sm">New index recommendations</p>
{isLoadingExtensions ? (
<GenericSkeletonLoader />
- ) : !isIndexAdvisorAvailable ? (
+ ) : !isAdvisorAvailable ? (
<IndexAdvisorDisabledState />
) : (
<>
@@ -212,12 +217,12 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
</AlertDescription_Shadcn_>
</Alert_Shadcn_>
) : (
- <p className="text-sm text-foreground-light">
- Creating the following {index_statements.length > 1 ? 'indexes' : 'index'}{' '}
- on <code className="text-xs">public.files</code> can improve this query's
- performance by{' '}
- <span className="text-brand">{totalImprovement.toFixed(2)}%</span>:
- </p>
+ <IndexImprovementText
+ indexStatements={index_statements}
+ totalCostBefore={total_cost_before}
+ totalCostAfter={total_cost_after}
+ className="text-sm text-foreground-light"
+ />
)}
<CodeBlock
hideLineNumbers
@@ -241,7 +246,7 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
</>
)}
</div>
- {isIndexAdvisorAvailable && hasIndexRecommendation && (
+ {isAdvisorAvailable && hasIndexRecommendation && (
<>
<div className="flex flex-col gap-y-2">
<p className="text-sm">Query costs</p>
@@ -306,7 +311,7 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {
)}
</QueryPanelSection>
- {isIndexAdvisorAvailable && hasIndexRecommendation && (
+ {isAdvisorAvailable && hasIndexRecommendation && (
<div className="bg-studio sticky bottom-0 border-t py-3 flex items-center justify-between px-5">
<div className="flex flex-col gap-y-1 text-sm">
<span>Apply index to database</span>
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts
index e787e221407..b142b0d3fb0 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts
@@ -4,6 +4,12 @@ export enum QUERY_PERFORMANCE_REPORT_TYPES {
SLOWEST_EXECUTION = 'slowest_execution',
}
+export const QUERY_PERFORMANCE_PRESET_MAP = {
+ [QUERY_PERFORMANCE_REPORT_TYPES.MOST_TIME_CONSUMING]: 'mostTimeConsuming',
+ [QUERY_PERFORMANCE_REPORT_TYPES.MOST_FREQUENT]: 'mostFrequentlyInvoked',
+ [QUERY_PERFORMANCE_REPORT_TYPES.SLOWEST_EXECUTION]: 'slowestExecutionTime',
+} as const
+
export const QUERY_PERFORMANCE_REPORTS = {
[QUERY_PERFORMANCE_REPORT_TYPES.MOST_TIME_CONSUMING]: [
{ id: 'query', name: 'Query', description: undefined, minWidth: 600 },
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx
index 0dbe8fdd746..b48872a14d3 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx
@@ -1,6 +1,6 @@
import { InformationCircleIcon } from '@heroicons/react/16/solid'
import { X } from 'lucide-react'
-import { useRouter } from 'next/router'
+import { parseAsString, useQueryStates } from 'nuqs'
import { useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
@@ -42,18 +42,21 @@ export const QueryPerformance = ({
queryHitRate,
queryPerformanceQuery,
}: QueryPerformanceProps) => {
- const router = useRouter()
- const { ref, preset } = useParams()
+ const { ref } = useParams()
const { project } = useProjectContext()
const state = useDatabaseSelectorStateSnapshot()
+ const [{ preset }, setSearchParams] = useQueryStates({
+ sort: parseAsString,
+ search: parseAsString,
+ order: parseAsString,
+ preset: parseAsString.withDefault(QUERY_PERFORMANCE_REPORT_TYPES.MOST_TIME_CONSUMING),
+ })
+
const { isLoading, isRefetching } = queryPerformanceQuery
const isPrimaryDatabase = state.selectedDatabaseId === ref
const formattedDatabaseId = formatDatabaseID(state.selectedDatabaseId ?? '')
- const [page, setPage] = useState<QUERY_PERFORMANCE_REPORT_TYPES>(
- (preset as QUERY_PERFORMANCE_REPORT_TYPES) ?? QUERY_PERFORMANCE_REPORT_TYPES.MOST_TIME_CONSUMING
- )
const [showResetgPgStatStatements, setShowResetgPgStatStatements] = useState(false)
const [showBottomSection, setShowBottomSection] = useLocalStorageQuery(
@@ -127,12 +130,9 @@ export const QueryPerformance = ({
return (
<>
<Tabs_Shadcn_
- defaultValue={page}
- onValueChange={(value) => {
- setPage(value as QUERY_PERFORMANCE_REPORT_TYPES)
- const { sort, search, ...rest } = router.query
- router.push({ ...router, query: { ...rest, preset: value } })
- }}
+ value={preset}
+ defaultValue={preset}
+ onValueChange={(value) => setSearchParams({ preset: value })}
>
<TabsList_Shadcn_ className={cn('flex gap-0 border-0 items-end z-10')}>
{QUERY_PERFORMANCE_TABS.map((tab) => {
@@ -152,14 +152,14 @@ export const QueryPerformance = ({
'group relative',
'px-6 py-3 border-b-0 flex flex-col items-start !shadow-none border-default border-t',
'even:border-x last:border-r even:!border-x-strong last:!border-r-strong',
- tab.id === page ? '!bg-surface-200' : '!bg-surface-200/[33%]',
+ tab.id === preset ? '!bg-surface-200' : '!bg-surface-200/[33%]',
'hover:!bg-surface-100',
'data-[state=active]:!bg-surface-200',
'hover:text-foreground-light',
'transition'
)}
>
- {tab.id === page && (
+ {tab.id === preset && (
<div className="absolute top-0 left-0 w-full h-[1px] bg-foreground" />
)}
@@ -189,7 +189,7 @@ export const QueryPerformance = ({
</span>
)}
- {tab.id === page && (
+ {tab.id === preset && (
<div className="absolute bottom-0 left-0 w-full h-[1px] bg-surface-200"></div>
)}
</TabsTrigger_Shadcn_>
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx
index 2e4b546c7be..c233ce7f2c8 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx
@@ -34,6 +34,7 @@ export const QueryPerformanceFilterBar = ({
LOCAL_STORAGE_KEYS.QUERY_PERF_SHOW_BOTTOM_SECTION,
true
)
+
const defaultSearchQueryValue = router.query.search ? String(router.query.search) : ''
const defaultFilterRoles = router.query.roles ? (router.query.roles as string[]) : []
const defaultSortByValue = router.query.sort
@@ -47,7 +48,7 @@ export const QueryPerformanceFilterBar = ({
})
// [Joshen] This is for the old UI, can deprecated after
const [sortByValue, setSortByValue] = useState<QueryPerformanceSort>(
- defaultSortByValue ?? { column: 'prop_total_time', order: 'desc' }
+ defaultSortByValue ?? { column: 'total_time', order: 'desc' }
)
const { isLoading, isRefetching } = queryPerformanceQuery
@@ -83,8 +84,8 @@ export const QueryPerformanceFilterBar = ({
}
const onSortChange = (order: 'asc' | 'desc') => {
- setSortByValue({ column: 'prop_total_time', order })
- router.push({ ...router, query: { ...router.query, sort: 'prop_total_time', order } })
+ setSortByValue({ column: 'total_time', order })
+ router.push({ ...router, query: { ...router.query, sort: 'total_time', order } })
}
return (
@@ -100,9 +101,11 @@ export const QueryPerformanceFilterBar = ({
activeOptions={isLoadingRoles ? [] : filters.roles}
onSaveFilters={onFilterRolesChange}
/>
+
<TextSearchPopover name="Query" value={searchInputVal} onSaveText={onSearchQueryChange} />
<div className="border-r border-strong h-6" />
+
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button icon={sortByValue?.order === 'desc' ? <ArrowDown /> : <ArrowUp />}>
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
index e5d9bec3704..127ec8dd8c8 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
@@ -18,6 +18,8 @@ import {
} from 'ui'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { QueryPerformanceSort } from '../Reports/Reports.queries'
+import { hasIndexRecommendations } from './index-advisor.utils'
+import { IndexSuggestionIcon } from './IndexSuggestionIcon'
import { QueryDetail } from './QueryDetail'
import { QueryIndexes } from './QueryIndexes'
import {
@@ -33,7 +35,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
const router = useRouter()
const gridRef = useRef<DataGridHandle>(null)
const { preset, sort: urlSort, order, roles, search } = useParams()
- const { isLoading } = queryPerformanceQuery
+ const { isLoading, data } = queryPerformanceQuery
const defaultSortValue = router.query.sort
? ({ column: router.query.sort, order: router.query.order } as QueryPerformanceSort)
@@ -70,8 +72,30 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
},
renderCell: (props) => {
const value = props.row?.[col.id]
+ if (col.id === 'query') {
+ return (
+ <div className="w-full flex items-center gap-x-2">
+ {hasIndexRecommendations(props.row.index_advisor_result, true) && (
+ <IndexSuggestionIcon
+ indexAdvisorResult={props.row.index_advisor_result}
+ onClickIcon={() => {
+ setSelectedRow(props.rowIdx)
+ setView('suggestion')
+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: props.rowIdx })
+ }}
+ />
+ )}
+ <div className="font-mono text-xs">{value}</div>
+ </div>
+ )
+ }
+
const isTime = col.name.includes('time')
- const formattedValue = isTime ? `${value.toFixed(0)}ms` : value.toLocaleString()
+ const formattedValue = !!value
+ ? isTime
+ ? `${value.toFixed(0)}ms`
+ : value.toLocaleString()
+ : ''
return (
<div
className={cn(
@@ -88,13 +112,14 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
return result
})
- const selectedQuery =
- selectedRow !== undefined ? queryPerformanceQuery.data?.[selectedRow]?.['query'] : undefined
+ const reportData = data ?? []
+ const selectedQuery = selectedRow !== undefined ? reportData[selectedRow]?.query : undefined
const query = (selectedQuery ?? '').trim().toLowerCase()
const showIndexSuggestions =
- query.startsWith('select') ||
- query.startsWith('with pgrst_source') ||
- query.startsWith('with pgrst_payload')
+ (query.startsWith('select') ||
+ query.startsWith('with pgrst_source') ||
+ query.startsWith('with pgrst_payload')) &&
+ hasIndexRecommendations(reportData[selectedRow!]?.index_advisor_result, true)
const onSortChange = (column: string) => {
let updatedSort = undefined
@@ -140,7 +165,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
rowHeight={44}
headerRowHeight={36}
columns={columns}
- rows={queryPerformanceQuery?.data ?? []}
+ rows={reportData}
rowClass={(_, idx) => {
const isSelected = idx === selectedRow
return [
@@ -161,8 +186,8 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
setSelectedRow(idx)
gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })
- const selectedQuery = queryPerformanceQuery.data[idx]['query']
- if (!(selectedQuery ?? '').trim().toLowerCase().startsWith('select')) {
+ const rowQuery = reportData[idx]?.query ?? ''
+ if (!rowQuery.trim().toLowerCase().startsWith('select')) {
setView('details')
}
}
@@ -225,7 +250,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
>
<QueryDetail
reportType={reportType}
- selectedRow={queryPerformanceQuery.data?.[selectedRow]}
+ selectedRow={reportData[selectedRow]}
onClickViewSuggestion={() => setView('suggestion')}
/>
</TabsContent_Shadcn_>
@@ -233,7 +258,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
value="suggestion"
className="mt-0 flex-grow min-h-0 overflow-y-auto"
>
- <QueryIndexes selectedRow={queryPerformanceQuery.data?.[selectedRow]} />
+ <QueryIndexes selectedRow={reportData[selectedRow]} />
</TabsContent_Shadcn_>
</Tabs_Shadcn_>
</ResizablePanel>
diff --git a/apps/studio/components/interfaces/QueryPerformance/TextSearchPopover.tsx b/apps/studio/components/interfaces/QueryPerformance/TextSearchPopover.tsx
index 17ce5f03439..adbff893682 100644
--- a/apps/studio/components/interfaces/QueryPerformance/TextSearchPopover.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/TextSearchPopover.tsx
@@ -45,7 +45,7 @@ export const TextSearchPopover = ({
</div>
</Button>
</PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">
+ <PopoverContent_Shadcn_ portal className="p-0" side="bottom" align="start">
<div className="space-y-4 p-3 min-w-[170px]">
<TextArea_Shadcn_
value={search}
diff --git a/apps/studio/components/interfaces/QueryPerformance/hooks/useIndexInvalidation.ts b/apps/studio/components/interfaces/QueryPerformance/hooks/useIndexInvalidation.ts
new file mode 100644
index 00000000000..63a53531afc
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/hooks/useIndexInvalidation.ts
@@ -0,0 +1,49 @@
+import { useQueryClient } from '@tanstack/react-query'
+import { useRouter } from 'next/router'
+import { parseAsString, useQueryStates } from 'nuqs'
+import { useCallback } from 'react'
+
+import {
+ QueryPerformanceSort,
+ useQueryPerformanceQuery,
+} from 'components/interfaces/Reports/Reports.queries'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { databaseIndexesKeys } from 'data/database-indexes/keys'
+import { databaseKeys } from 'data/database/keys'
+import {
+ QUERY_PERFORMANCE_PRESET_MAP,
+ QUERY_PERFORMANCE_REPORT_TYPES,
+} from '../QueryPerformance.constants'
+import { useIsIndexAdvisorAvailable } from './useIsIndexAdvisorAvailable'
+
+export function useIndexInvalidation() {
+ const router = useRouter()
+ const queryClient = useQueryClient()
+ const { project } = useProjectContext()
+ const isAdvisorAvailable = useIsIndexAdvisorAvailable()
+
+ const [{ preset: urlPreset, search: searchQuery, order, sort }] = useQueryStates({
+ sort: parseAsString,
+ search: parseAsString.withDefault(''),
+ order: parseAsString,
+ preset: parseAsString.withDefault(QUERY_PERFORMANCE_REPORT_TYPES.MOST_TIME_CONSUMING),
+ })
+
+ const preset = QUERY_PERFORMANCE_PRESET_MAP[urlPreset as QUERY_PERFORMANCE_REPORT_TYPES]
+ const orderBy = !!sort ? ({ column: sort, order } as QueryPerformanceSort) : undefined
+ const roles = router?.query?.roles ?? []
+
+ const queryPerformanceQuery = useQueryPerformanceQuery({
+ searchQuery,
+ orderBy,
+ preset,
+ roles: typeof roles === 'string' ? [roles] : roles,
+ runIndexAdvisor: isAdvisorAvailable,
+ })
+
+ return useCallback(() => {
+ queryPerformanceQuery.runQuery()
+ queryClient.invalidateQueries(databaseKeys.indexAdvisorFromQuery(project?.ref, ''))
+ queryClient.invalidateQueries(databaseIndexesKeys.list(project?.ref))
+ }, [queryPerformanceQuery, queryClient, project?.ref])
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorAvailable.ts b/apps/studio/components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorAvailable.ts
new file mode 100644
index 00000000000..10e637eb8ee
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorAvailable.ts
@@ -0,0 +1,18 @@
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { getIndexAdvisorExtensions } from 'components/interfaces/QueryPerformance/index-advisor.utils'
+
+/**
+ * Hook to check if index advisor functionality is available
+ * @returns boolean indicating if index advisor is available
+ */
+export function useIsIndexAdvisorAvailable(): boolean {
+ const { project } = useProjectContext()
+ const { data: extensions } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const { hypopg, indexAdvisor } = getIndexAdvisorExtensions(extensions ?? [])
+ return hypopg?.installed_version !== null && indexAdvisor?.installed_version !== null
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/index-advisor.utils.ts b/apps/studio/components/interfaces/QueryPerformance/index-advisor.utils.ts
new file mode 100644
index 00000000000..d8e79d0e2f0
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/index-advisor.utils.ts
@@ -0,0 +1,103 @@
+import { toast } from 'sonner'
+
+import { DatabaseExtension } from 'data/database-extensions/database-extensions-query'
+import { GetIndexAdvisorResultResponse } from 'data/database/retrieve-index-advisor-result-query'
+import { executeSql } from 'data/sql/execute-sql-query'
+
+/**
+ * Gets the required extensions for index advisor
+ * @param extensions Array of database extensions
+ * @returns Object containing hypopg and index_advisor extensions if they exist
+ */
+export function getIndexAdvisorExtensions(extensions: DatabaseExtension[] = []) {
+ const hypopg = extensions.find((ext) => ext.name === 'hypopg')
+ const indexAdvisor = extensions.find((ext) => ext.name === 'index_advisor')
+ return { hypopg, indexAdvisor }
+}
+
+/**
+ * Calculates the percentage improvement between before and after costs
+ *
+ * @param costBefore Cost before optimization
+ * @param costAfter Cost after optimization
+ * @returns Percentage improvement, or 0 if inputs are invalid
+ */
+export function calculateImprovement(
+ costBefore: number | undefined,
+ costAfter: number | undefined
+): number {
+ if (
+ costBefore === undefined ||
+ costAfter === undefined ||
+ costBefore <= 0 ||
+ costBefore <= costAfter
+ ) {
+ return 0
+ }
+
+ return ((costBefore - costAfter) / costBefore) * 100
+}
+
+interface CreateIndexParams {
+ projectRef?: string
+ connectionString?: string
+ indexStatements: string[]
+ onSuccess?: () => void
+ onError?: (error: any) => void
+}
+
+/**
+ * Creates database indexes using the provided SQL statements
+ *
+ * @param params Parameters for index creation
+ * @returns Promise that resolves when the index creation completes
+ */
+export async function createIndexes({
+ projectRef,
+ connectionString,
+ indexStatements,
+ onSuccess,
+ onError,
+}: CreateIndexParams): Promise<void> {
+ if (!projectRef) {
+ const error = new Error('Project ref is required')
+ if (onError) onError(error)
+ return Promise.reject(error)
+ }
+
+ if (indexStatements.length === 0) {
+ const error = new Error('No index statements provided')
+ if (onError) onError(error)
+ return Promise.reject(error)
+ }
+
+ try {
+ await executeSql({
+ projectRef,
+ connectionString,
+ sql: indexStatements.join(';\n') + ';',
+ })
+
+ toast.success('Successfully created index')
+ if (onSuccess) onSuccess()
+ return Promise.resolve()
+ } catch (error: any) {
+ toast.error(`Failed to create index: ${error.message}`)
+ if (onError) onError(error)
+ return Promise.reject(error)
+ }
+}
+
+/**
+ * Checks if the index advisor result contains recommendations
+ *
+ * @param result The index advisor result object
+ * @param isSuccess Whether the query was successful
+ * @returns Whether there are index recommendations available
+ */
+export function hasIndexRecommendations(
+ result: GetIndexAdvisorResultResponse | undefined,
+ isSuccess: boolean
+): boolean {
+ return Boolean(isSuccess && result?.index_statements && result.index_statements.length > 0)
+}
diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.ts b/apps/studio/components/interfaces/Reports/Reports.constants.ts
index aa9866308b9..1eb5f9310d2 100644
--- a/apps/studio/components/interfaces/Reports/Reports.constants.ts
+++ b/apps/studio/components/interfaces/Reports/Reports.constants.ts
@@ -1,8 +1,8 @@
import dayjs from 'dayjs'
+import { PlanId } from 'data/subscriptions/types'
import type { DatetimeHelper } from '../Settings/Logs/Logs.types'
import { PresetConfig, Presets, ReportFilterItem } from './Reports.types'
-import { PlanId } from 'data/subscriptions/types'
export const LAYOUT_COLUMN_COUNT = 2
@@ -319,7 +319,7 @@ limit 12
queries: {
mostFrequentlyInvoked: {
queryType: 'db',
- sql: (_params, where, orderBy) => `
+ sql: (_params, where, orderBy, runIndexAdvisor = false) => `
-- Most frequently called queries
set search_path to public, extensions;
@@ -337,16 +337,35 @@ select
-- min_time,
-- max_time,
-- mean_time,
- statements.rows / statements.calls as avg_rows
+ statements.rows / statements.calls as avg_rows${
+ runIndexAdvisor
+ ? `,
+ case
+ when (lower(statements.query) like 'select%' or lower(statements.query) like 'with pgrst%')
+ then (
+ select json_build_object(
+ 'has_suggestion', array_length(index_statements, 1) > 0,
+ 'startup_cost_before', startup_cost_before,
+ 'startup_cost_after', startup_cost_after,
+ 'total_cost_before', total_cost_before,
+ 'total_cost_after', total_cost_after,
+ 'index_statements', index_statements
+ )
+ from index_advisor(statements.query)
+ )
+ else null
+ end as index_advisor_result`
+ : ''
+ }
from pg_stat_statements as statements
inner join pg_authid as auth on statements.userid = auth.oid
${where || ''}
${orderBy || 'order by statements.calls desc'}
- limit 20;`,
+ limit 20`,
},
mostTimeConsuming: {
queryType: 'db',
- sql: (_, where, orderBy) => `
+ sql: (_, where, orderBy, runIndexAdvisor = false) => `
-- Most time consuming queries
set search_path to public, extensions;
@@ -355,16 +374,35 @@ select
statements.query,
statements.calls,
statements.total_exec_time + statements.total_plan_time as total_time,
- to_char(((statements.total_exec_time + statements.total_plan_time)/sum(statements.total_exec_time + statements.total_plan_time) OVER()) * 100, 'FM90D0') || '%' AS prop_total_time
+ to_char(((statements.total_exec_time + statements.total_plan_time)/sum(statements.total_exec_time + statements.total_plan_time) OVER()) * 100, 'FM90D0') || '%' AS prop_total_time${
+ runIndexAdvisor
+ ? `,
+ case
+ when (lower(statements.query) like 'select%' or lower(statements.query) like 'with pgrst%')
+ then (
+ select json_build_object(
+ 'has_suggestion', array_length(index_statements, 1) > 0,
+ 'startup_cost_before', startup_cost_before,
+ 'startup_cost_after', startup_cost_after,
+ 'total_cost_before', total_cost_before,
+ 'total_cost_after', total_cost_after,
+ 'index_statements', index_statements
+ )
+ from index_advisor(statements.query)
+ )
+ else null
+ end as index_advisor_result`
+ : ''
+ }
from pg_stat_statements as statements
inner join pg_authid as auth on statements.userid = auth.oid
${where || ''}
${orderBy || 'order by total_time desc'}
- limit 20;`,
+ limit 20`,
},
slowestExecutionTime: {
queryType: 'db',
- sql: (_params, where, orderBy) => `
+ sql: (_params, where, orderBy, runIndexAdvisor = false) => `
-- Slowest queries by max execution time
set search_path to public, extensions;
@@ -382,7 +420,26 @@ select
-- min_time,
-- max_time,
-- mean_time,
- statements.rows / statements.calls as avg_rows
+ statements.rows / statements.calls as avg_rows${
+ runIndexAdvisor
+ ? `,
+ case
+ when (lower(statements.query) like 'select%' or lower(statements.query) like 'with pgrst%')
+ then (
+ select json_build_object(
+ 'has_suggestion', array_length(index_statements, 1) > 0,
+ 'startup_cost_before', startup_cost_before,
+ 'startup_cost_after', startup_cost_after,
+ 'total_cost_before', total_cost_before,
+ 'total_cost_after', total_cost_after,
+ 'index_statements', index_statements
+ )
+ from index_advisor(statements.query)
+ )
+ else null
+ end as index_advisor_result`
+ : ''
+ }
from pg_stat_statements as statements
inner join pg_authid as auth on statements.userid = auth.oid
${where || ''}
diff --git a/apps/studio/components/interfaces/Reports/Reports.queries.ts b/apps/studio/components/interfaces/Reports/Reports.queries.ts
index 9c453a8cf69..f4d0d6da68d 100644
--- a/apps/studio/components/interfaces/Reports/Reports.queries.ts
+++ b/apps/studio/components/interfaces/Reports/Reports.queries.ts
@@ -1,7 +1,6 @@
-import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
+import useDbQuery from 'hooks/analytics/useDbQuery'
import { PRESET_CONFIG } from './Reports.constants'
import { Presets } from './Reports.types'
-import useDbQuery from 'hooks/analytics/useDbQuery'
export type QueryPerformanceSort = {
column:
@@ -15,11 +14,12 @@ export type QueryPerformanceSort = {
order: 'asc' | 'desc'
}
-type QueryPerformanceQueryOpts = {
+export type QueryPerformanceQueryOpts = {
preset: 'mostFrequentlyInvoked' | 'mostTimeConsuming' | 'slowestExecutionTime' | 'queryHitRate'
searchQuery?: string
orderBy?: QueryPerformanceSort
roles?: string[]
+ runIndexAdvisor?: boolean
}
export const useQueryPerformanceQuery = ({
@@ -27,6 +27,7 @@ export const useQueryPerformanceQuery = ({
orderBy,
searchQuery = '',
roles,
+ runIndexAdvisor = false,
}: QueryPerformanceQueryOpts) => {
const queryPerfQueries = PRESET_CONFIG[Presets.QUERY_PERFORMANCE]
const baseSQL = queryPerfQueries.queries[preset]
@@ -41,7 +42,12 @@ export const useQueryPerformanceQuery = ({
.join(' AND ')
const orderBySql = orderBy && `ORDER BY ${orderBy.column} ${orderBy.order}`
- const sql = baseSQL.sql([], whereSql.length > 0 ? `WHERE ${whereSql}` : undefined, orderBySql)
+ const sql = baseSQL.sql(
+ [],
+ whereSql.length > 0 ? `WHERE ${whereSql}` : undefined,
+ orderBySql,
+ runIndexAdvisor
+ )
return useDbQuery({
sql,
params: undefined,
diff --git a/apps/studio/components/interfaces/Reports/Reports.types.ts b/apps/studio/components/interfaces/Reports/Reports.types.ts
index 17e18e61120..6767386aefd 100644
--- a/apps/studio/components/interfaces/Reports/Reports.types.ts
+++ b/apps/studio/components/interfaces/Reports/Reports.types.ts
@@ -20,7 +20,12 @@ export type BaseQueries<Keys extends string> = Record<Keys, ReportQuery>
export interface ReportQuery {
queryType: ReportQueryType
- sql: (filters: ReportFilterItem[], where?: string, orderBy?: string) => string
+ sql: (
+ filters: ReportFilterItem[],
+ where?: string,
+ orderBy?: string,
+ runIndexAdvisor?: boolean
+ ) => string
}
export type ReportQueryType = 'db' | 'logs'
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
index acad23a436b..60827c734a0 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
@@ -1,5 +1,6 @@
import { authKeys } from 'data/auth/keys'
import { databaseExtensionsKeys } from 'data/database-extensions/keys'
+import { databaseIndexesKeys } from 'data/database-indexes/keys'
import { databasePoliciesKeys } from 'data/database-policies/keys'
import { databaseTriggerKeys } from 'data/database-triggers/keys'
import { databaseKeys } from 'data/database/keys'
@@ -93,7 +94,7 @@ export const getContextualInvalidationKeys = ({
'database/triggers': [databaseTriggerKeys.list(ref)],
'database/types': [enumeratedTypesKeys.list(ref)],
'database/extensions': [databaseExtensionsKeys.list(ref)],
- 'database/indexes': [databaseKeys.indexes(ref, schema)],
+ 'database/indexes': [databaseIndexesKeys.list(ref, schema)],
} as const
)[key] ?? []
)
diff --git a/apps/studio/data/database-indexes/index-create-mutation.ts b/apps/studio/data/database-indexes/index-create-mutation.ts
new file mode 100644
index 00000000000..2f7fbe3bf3f
--- /dev/null
+++ b/apps/studio/data/database-indexes/index-create-mutation.ts
@@ -0,0 +1,72 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseIndexesKeys } from './keys'
+
+export type DatabaseIndexCreateVariables = {
+ projectRef: string
+ connectionString?: string
+ payload: {
+ schema: string
+ entity: string
+ type: string
+ columns: string[]
+ }
+}
+
+export async function createDatabaseIndex({
+ projectRef,
+ connectionString,
+ payload,
+}: DatabaseIndexCreateVariables) {
+ const { schema, entity, type, columns } = payload
+
+ const sql = `
+ CREATE INDEX ON "${schema}"."${entity}" USING ${type} (${columns
+ .map((column) => `"${column}"`)
+ .join(', ')});
+ `.trim()
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['indexes', schema],
+ })
+
+ return result
+}
+
+type DatabaseIndexCreateData = Awaited<ReturnType<typeof createDatabaseIndex>>
+
+export const useDatabaseIndexCreateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseIndexCreateData, ResponseError, DatabaseIndexCreateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseIndexCreateData, ResponseError, DatabaseIndexCreateVariables>(
+ (vars) => createDatabaseIndex(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseIndexesKeys.list(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to create database index: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database-indexes/index-delete-mutation.ts b/apps/studio/data/database-indexes/index-delete-mutation.ts
new file mode 100644
index 00000000000..2384bb18088
--- /dev/null
+++ b/apps/studio/data/database-indexes/index-delete-mutation.ts
@@ -0,0 +1,61 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseIndexesKeys } from './keys'
+
+export type DatabaseIndexDeleteVariables = {
+ projectRef: string
+ connectionString?: string
+ name: string
+}
+
+export async function deleteDatabaseIndex({
+ projectRef,
+ connectionString,
+ name,
+}: DatabaseIndexDeleteVariables) {
+ const sql = `drop index if exists "${name}"`
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['indexes'],
+ })
+
+ return result
+}
+
+type DatabaseIndexDeleteData = Awaited<ReturnType<typeof deleteDatabaseIndex>>
+
+export const useDatabaseIndexDeleteMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseIndexDeleteData, ResponseError, DatabaseIndexDeleteVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseIndexDeleteData, ResponseError, DatabaseIndexDeleteVariables>(
+ (vars) => deleteDatabaseIndex(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseIndexesKeys.list(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to delete database index: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database/indexes-query.ts b/apps/studio/data/database-indexes/indexes-query.ts
similarity index 94%
rename from apps/studio/data/database/indexes-query.ts
rename to apps/studio/data/database-indexes/indexes-query.ts
index 35a351890d6..c108187ab80 100644
--- a/apps/studio/data/database/indexes-query.ts
+++ b/apps/studio/data/database-indexes/indexes-query.ts
@@ -1,6 +1,6 @@
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
-import { databaseKeys } from './keys'
+import { databaseIndexesKeys } from './keys'
type GetIndexesArgs = {
schema?: string
@@ -58,7 +58,7 @@ export const useIndexesQuery = <TData = IndexesData>(
{ enabled = true, ...options }: UseQueryOptions<IndexesData, IndexesError, TData> = {}
) =>
useQuery<IndexesData, IndexesError, TData>(
- databaseKeys.indexes(projectRef, schema),
+ databaseIndexesKeys.list(projectRef, schema),
({ signal }) => getIndexes({ projectRef, connectionString, schema }, signal),
{
enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined',
diff --git a/apps/studio/data/database-indexes/keys.ts b/apps/studio/data/database-indexes/keys.ts
new file mode 100644
index 00000000000..989a1c26f60
--- /dev/null
+++ b/apps/studio/data/database-indexes/keys.ts
@@ -0,0 +1,4 @@
+export const databaseIndexesKeys = {
+ list: (projectRef: string | undefined, schema?: string) =>
+ ['projects', projectRef, 'database-indexes', schema].filter(Boolean),
+}
diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.ts
index 84550d6fe2b..a71e1032ac3 100644
--- a/apps/studio/data/database/keys.ts
+++ b/apps/studio/data/database/keys.ts
@@ -1,7 +1,5 @@
export const databaseKeys = {
schemas: (projectRef: string | undefined) => ['projects', projectRef, 'schemas'] as const,
- indexes: (projectRef: string | undefined, schema?: string) =>
- ['projects', projectRef, 'indexes', schema].filter(Boolean),
keywords: (projectRef: string | undefined) => ['projects', projectRef, 'keywords'] as const,
migrations: (projectRef: string | undefined) => ['projects', projectRef, 'migrations'] as const,
tableColumns: (
diff --git a/apps/studio/hooks/analytics/useLogsUrlState.ts b/apps/studio/hooks/analytics/useLogsUrlState.ts
index 73cf6a6d8d5..9817dfacc6f 100644
--- a/apps/studio/hooks/analytics/useLogsUrlState.ts
+++ b/apps/studio/hooks/analytics/useLogsUrlState.ts
@@ -1,5 +1,5 @@
import { createParser, useQueryState } from 'nuqs'
-import { LogsTableName } from 'components/interfaces/Settings/Logs/Logs.constants'
+
import { Filters } from 'components/interfaces/Settings/Logs/Logs.types'
interface LogsUrlState {
diff --git a/apps/studio/pages/project/[ref]/advisors/query-performance.tsx b/apps/studio/pages/project/[ref]/advisors/query-performance.tsx
index be76267a2f2..a708945b102 100644
--- a/apps/studio/pages/project/[ref]/advisors/query-performance.tsx
+++ b/apps/studio/pages/project/[ref]/advisors/query-performance.tsx
@@ -1,8 +1,14 @@
import { useRouter } from 'next/router'
+import { parseAsString, useQueryStates } from 'nuqs'
import { useParams } from 'common'
+import { EnableIndexAdvisorButton } from 'components/interfaces/QueryPerformance/EnableIndexAdvisorButton'
+import { useIsIndexAdvisorAvailable } from 'components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorAvailable'
import { QueryPerformance } from 'components/interfaces/QueryPerformance/QueryPerformance'
-import { QUERY_PERFORMANCE_REPORT_TYPES } from 'components/interfaces/QueryPerformance/QueryPerformance.constants'
+import {
+ QUERY_PERFORMANCE_PRESET_MAP,
+ QUERY_PERFORMANCE_REPORT_TYPES,
+} from 'components/interfaces/QueryPerformance/QueryPerformance.constants'
import { PRESET_CONFIG } from 'components/interfaces/Reports/Reports.constants'
import {
QueryPerformanceSort,
@@ -11,38 +17,38 @@ import {
import { Presets } from 'components/interfaces/Reports/Reports.types'
import { queriesFactory } from 'components/interfaces/Reports/Reports.utils'
import AdvisorsLayout from 'components/layouts/AdvisorsLayout/AdvisorsLayout'
+import DefaultLayout from 'components/layouts/DefaultLayout'
import DatabaseSelector from 'components/ui/DatabaseSelector'
+import { DocsButton } from 'components/ui/DocsButton'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import type { NextPageWithLayout } from 'types'
-import DefaultLayout from 'components/layouts/DefaultLayout'
-
-const PRESET_MAP = {
- [QUERY_PERFORMANCE_REPORT_TYPES.MOST_TIME_CONSUMING]: 'mostTimeConsuming',
- [QUERY_PERFORMANCE_REPORT_TYPES.MOST_FREQUENT]: 'mostFrequentlyInvoked',
- [QUERY_PERFORMANCE_REPORT_TYPES.SLOWEST_EXECUTION]: 'slowestExecutionTime',
-} as const
const QueryPerformanceReport: NextPageWithLayout = () => {
const router = useRouter()
- const { ref: projectRef, search, sort, order, preset: urlPreset } = useParams()
+ const { ref: projectRef } = useParams()
+ const isAdvisorAvailable = useIsIndexAdvisorAvailable()
+
+ const [{ preset: urlPreset, search: searchQuery, order, sort }] = useQueryStates({
+ sort: parseAsString,
+ search: parseAsString.withDefault(''),
+ order: parseAsString,
+ preset: parseAsString.withDefault(QUERY_PERFORMANCE_REPORT_TYPES.MOST_TIME_CONSUMING),
+ })
const config = PRESET_CONFIG[Presets.QUERY_PERFORMANCE]
const hooks = queriesFactory(config.queries, projectRef ?? 'default')
const queryHitRate = hooks.queryHitRate()
- const orderBy = sort !== undefined ? ({ column: sort, order } as QueryPerformanceSort) : undefined
- const searchQuery = search ?? ''
+ const preset = QUERY_PERFORMANCE_PRESET_MAP[urlPreset as QUERY_PERFORMANCE_REPORT_TYPES]
+ const orderBy = !!sort ? ({ column: sort, order } as QueryPerformanceSort) : undefined
const roles = router?.query?.roles ?? []
- const preset =
- urlPreset !== undefined
- ? PRESET_MAP[urlPreset as QUERY_PERFORMANCE_REPORT_TYPES]
- : 'mostTimeConsuming'
const queryPerformanceQuery = useQueryPerformanceQuery({
searchQuery,
orderBy,
preset,
roles: typeof roles === 'string' ? [roles] : roles,
+ runIndexAdvisor: isAdvisorAvailable,
})
return (
@@ -50,8 +56,13 @@ const QueryPerformanceReport: NextPageWithLayout = () => {
<FormHeader
className="py-4 px-6 !mb-0"
title="Query Performance"
- docsUrl="https://supabase.com/docs/guides/platform/performance#examining-query-performance"
- actions={<DatabaseSelector />}
+ actions={
+ <div className="flex items-center gap-2">
+ <EnableIndexAdvisorButton />
+ <DocsButton href="https://supabase.com/docs/guides/platform/performance#examining-query-performance" />
+ <DatabaseSelector />
+ </div>
+ }
/>
<QueryPerformance queryHitRate={queryHitRate} queryPerformanceQuery={queryPerformanceQuery} />
</div>