The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Feat/integrate index advisor (#22641)
Joshen Limb07f8304e052
diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/IndexAdvisorDisabledState.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/IndexAdvisorDisabledState.tsxnew file mode 100644index 00000000000..8f277142a18--- /dev/null+++ b/apps/studio/components/interfaces/QueryPerformanceV2/IndexAdvisorDisabledState.tsx@@ -0,0 +1,74 @@+import { ExternalLink } from 'lucide-react'++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 { useIndexAdvisorEnableMutation } from 'data/database/index-advisor-enable-mutation'+import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'+import { Markdown } from '../Markdown'++export const IndexAdvisorDisabledState = () => {+ const { project } = useProjectContext()+ const { data: extensions } = useDatabaseExtensionsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })+ const hypopgExtension = (extensions ?? []).find((ext) => ext.name === 'hypopg')++ const { mutateAsync: enableExtension, isLoading: isEnablingExtension } =+ useDatabaseExtensionEnableMutation()+ const { mutateAsync: enableIndexAdvisor, isLoading: isEnablingIndexAdvisor } =+ useIndexAdvisorEnableMutation()+ const isEnabling = isEnablingExtension || isEnablingIndexAdvisor++ const onEnableIndexAdvisor = async () => {+ if (project === undefined) return console.error('Project is required')+ if (hypopgExtension?.installed_version === null) {+ await enableExtension({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ name: hypopgExtension.name,+ schema: hypopgExtension?.schema ?? 'extensions',+ version: hypopgExtension.default_version,+ })+ }++ // [Joshen] Once index_advisor ext is ready, it'll just be enabling an extension+ await enableIndexAdvisor({+ projectRef: project.ref,+ connectionString: project.connectionString,+ })+ }++ return (+ <Alert_Shadcn_>+ <AlertTitle_Shadcn_>+ Get index suggestions to improve your query performance+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ <Markdown content="The `index_advisor` extension can help in recommending database indexes to reduce the costs of your query." />+ </AlertDescription_Shadcn_>+ <AlertDescription_Shadcn_ className="mt-3">+ <div className="flex items-center gap-x-2">+ <Button+ type="default"+ disabled={isEnabling}+ loading={isEnabling}+ onClick={() => onEnableIndexAdvisor()}+ >+ Enable index advisor+ </Button>+ <Button asChild type="default" icon={<ExternalLink />}>+ <a+ target="_blank"+ rel="noreferrer"+ href="https://supabase.com/docs/guides/database/extensions/index_advisor"+ >+ Documentation+ </a>+ </Button>+ </div>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )+}diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/QueryDetail.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/QueryDetail.tsxindex c6e7c06be5d..f4236a5491d 100644--- a/apps/studio/components/interfaces/QueryPerformanceV2/QueryDetail.tsx+++ b/apps/studio/components/interfaces/QueryPerformanceV2/QueryDetail.tsx@@ -1,17 +1,33 @@-import { CodeBlock, cn } from 'ui'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ CodeBlock,+ cn,+} from 'ui'import {QUERY_PERFORMANCE_REPORTS,QUERY_PERFORMANCE_REPORT_TYPES,} from './QueryPerformance.constants'import { format } from 'sql-formatter'import { useEffect, useState } from 'react'+import { QueryPanelContainer, QueryPanelSection } from './QueryPanel'+import { Lightbulb } from 'lucide-react'interface QueryDetailProps {reportType: QUERY_PERFORMANCE_REPORT_TYPESselectedRow: any+ onClickViewSuggestion: () => void}-export const QueryDetail = ({ reportType, selectedRow }: QueryDetailProps) => {+export const QueryDetail = ({+ reportType,+ selectedRow,+ onClickViewSuggestion,+}: QueryDetailProps) => {+ // [Joshen] TODO implement this logic once the linter rules are in+ const isLinterWarning = falseconst report = QUERY_PERFORMANCE_REPORTS[reportType]const [query, setQuery] = useState(selectedRow?.['query'])@@ -30,8 +46,8 @@ export const QueryDetail = ({ reportType, selectedRow }: QueryDetailProps) => {}, [selectedRow])return (- <div className="flex flex-col gap-y-8 divide-y">- <div className="px-5 flex flex-col gap-y-2">+ <QueryPanelContainer>+ <QueryPanelSection><p className="text-sm">Query pattern</p><CodeBlockhideLineNumbers@@ -43,15 +59,33 @@ export const QueryDetail = ({ reportType, selectedRow }: QueryDetailProps) => {'[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap')}/>- </div>- <div className="py-4 px-5 flex flex-col gap-y-1">+ {isLinterWarning && (+ <Alert_Shadcn_+ variant="default"+ className="mt-2 border-brand-400 bg-alternative [&>svg]:p-0.5 [&>svg]:bg-transparent [&>svg]:text-brand"+ >+ <Lightbulb />+ <AlertTitle_Shadcn_>Suggested optimization: Add an index</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ Adding an index will help this query execute faster+ </AlertDescription_Shadcn_>+ <AlertDescription_Shadcn_>+ <Button className="mt-3" onClick={() => onClickViewSuggestion()}>+ View suggestion+ </Button>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}+ </QueryPanelSection>+ <div className="border-t" />+ <QueryPanelSection className="gap-y-1">{report.filter((x) => x.id !== 'query').map((x) => {const isTime = x.name.includes('time')const formattedValue = isTime- ? `${selectedRow[x.id].toFixed(2)}ms`- : String(selectedRow[x.id])+ ? `${selectedRow?.[x.id].toFixed(2)}ms`+ : String(selectedRow?.[x.id])return (<div key={x.id} className="flex gap-x-2"><p className="text-foreground-lighter text-sm w-32">{x.name}</p>@@ -59,7 +93,7 @@ export const QueryDetail = ({ reportType, selectedRow }: QueryDetailProps) => {</div>)})}- </div>- </div>+ </QueryPanelSection>+ </QueryPanelContainer>)}diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/QueryIndexes.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/QueryIndexes.tsxnew file mode 100644index 00000000000..1af555dd169--- /dev/null+++ b/apps/studio/components/interfaces/QueryPerformanceV2/QueryIndexes.tsx@@ -0,0 +1,326 @@+import { Check, Lightbulb, Table2 } from 'lucide-react'+import { useState } from 'react'+import toast from 'react-hot-toast'++import { AccordionTrigger } from '@ui/components/shadcn/ui/accordion'+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 { useExecuteSqlQuery } from 'data/sql/execute-sql-query'+import {+ AccordionContent_Shadcn_,+ AccordionItem_Shadcn_,+ Accordion_Shadcn_,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ CodeBlock,+ CollapsibleContent_Shadcn_,+ CollapsibleTrigger_Shadcn_,+ Collapsible_Shadcn_,+ cn,+} from 'ui'+import { GenericSkeletonLoader } from 'ui-patterns'+import { IndexAdvisorDisabledState } from './IndexAdvisorDisabledState'+import { QueryPanelContainer, QueryPanelScoreSection, QueryPanelSection } from './QueryPanel'++interface QueryIndexesProps {+ selectedRow: any+}++// [Joshen] There's several more UX things we can do to help ease the learning curve of indexes I think+// e.g understanding "costs", what numbers of "costs" are actually considered insignificant++export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {+ // [Joshen] TODO implement this logic once the linter rules are in+ const isLinterWarning = false+ const { project } = useProjectContext()+ const [showStartupCosts, setShowStartupCosts] = useState(false)++ const {+ data: usedIndexes,+ isSuccess,+ isLoading,+ } = useGetIndexesFromSelectQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ query: selectedRow?.['query'],+ })++ const { data: indexAdvisorExt, isLoading: isLoadingIndexAdvisorExt } = useExecuteSqlQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ sql: `select * from pg_proc where proname = 'index_advisor';`,+ queryKey: ['index-advisor-function-check'],+ })+ const { data: extensions, isLoading: isLoadingExtensions } = useDatabaseExtensionsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ const isLoadingChecks = isLoadingIndexAdvisorExt || isLoadingExtensions+ const hypopgExtension = (extensions ?? []).find((ext) => ext.name === 'hypopg')+ const isIndexAdvisorAvailable =+ (indexAdvisorExt?.result ?? []).length > 0 &&+ hypopgExtension !== undefined &&+ hypopgExtension.installed_version !== null++ const {+ data: indexAdvisorResult,+ error: indexAdvisorError,+ refetch,+ isError: isErrorIndexAdvisorResult,+ isSuccess: isSuccessIndexAdvisorResult,+ isLoading: isLoadingIndexAdvisorResult,+ } = useGetIndexAdvisorResult(+ {+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ query: selectedRow?.['query'],+ },+ { enabled: isIndexAdvisorAvailable }+ )++ const {+ index_statements,+ startup_cost_after,+ startup_cost_before,+ 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 { 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 createIndex = () => {+ if (index_statements.length === 0) return++ execute({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ sql: index_statements.join(';\n') + ';',+ })+ }++ return (+ <QueryPanelContainer className="h-full">+ <QueryPanelSection>+ <div>+ <p className="text-sm">Indexes in use</p>+ <p className="text-sm text-foreground-light">+ This query is using the following index{(usedIndexes ?? []).length > 1 ? 's' : ''}:+ </p>+ </div>+ {isLoading && <GenericSkeletonLoader />}+ {isSuccess && (+ <div>+ {usedIndexes.length === 0 && (+ <div className="border rounded border-dashed flex flex-col items-center justify-center py-4 px-20 gap-y-1">+ <p className="text-sm text-foreground-light">+ No indexes are involved in this query+ </p>+ <p className="text-center text-xs text-foreground-lighter">+ Indexes may not necessarily be used if they incur a higher cost when executing the+ query+ </p>+ </div>+ )}+ {usedIndexes.map((index) => {+ return (+ <div+ key={index.name}+ className="flex items-center gap-x-4 bg-surface-100 border first:rounded-tl first:rounded-tr border-b-0 last:border-b last:rounded-b px-2 py-2"+ >+ <div className="flex items-center gap-x-2">+ <Table2 size={14} className="text-foreground-light" />+ <span className="text-xs font-mono text-foreground-light">+ {index.schema}.{index.table}+ </span>+ </div>+ <span className="text-xs font-mono">{index.name}</span>+ </div>+ )+ })}+ </div>+ )}+ </QueryPanelSection>++ <div className="border-t" />++ <QueryPanelSection className="flex flex-col gap-y-6">+ <div className="flex flex-col gap-y-2">+ <p className="text-sm">New index recommendations</p>+ {isLoadingChecks ? (+ <GenericSkeletonLoader />+ ) : !isIndexAdvisorAvailable ? (+ <IndexAdvisorDisabledState />+ ) : (+ <>+ {isLoadingIndexAdvisorResult && <GenericSkeletonLoader />}+ {isErrorIndexAdvisorResult && (+ <AlertError+ ref={project?.ref}+ error={indexAdvisorError}+ subject="Failed to retrieve result from index advisor"+ />+ )}+ {isSuccessIndexAdvisorResult && (+ <>+ {(index_statements ?? []).length === 0 ? (+ <Alert_Shadcn_ className="[&>svg]:rounded-full">+ <Check />+ <AlertTitle_Shadcn_>This query is optimized</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ Recommendations for indexes will show here+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ ) : (+ <>+ {isLinterWarning ? (+ <Alert_Shadcn_+ variant="default"+ className="border-brand-400 bg-alternative [&>svg]:p-0.5 [&>svg]:bg-transparent [&>svg]:text-brand"+ >+ <Lightbulb />+ <AlertTitle_Shadcn_>+ We have {index_statements.length} index recommendation+ {index_statements.length > 1 ? 's' : ''}+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ You can improve this query's performance by{' '}+ <span className="text-brand">{totalImprovement.toFixed(2)}%</span> by+ adding the following suggested{' '}+ {index_statements.length > 1 ? 'indexes' : 'index'}+ </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>+ )}+ <CodeBlock+ hideLineNumbers+ value={index_statements.join(';\n') + ';'}+ language="sql"+ className={cn(+ 'max-w-full max-h-[310px]',+ '!py-3 !px-3.5 prose dark:prose-dark transition',+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap'+ )}+ />+ <p className="text-sm text-foreground-light">+ This recommendation serves to prevent your queries from slowing down as your+ application grows, and hence the index may not be used immediately after+ it's created. (e.g If your table is still small at this time)+ </p>+ </>+ )}+ </>+ )}+ </>+ )}+ </div>+ {isIndexAdvisorAvailable && hasIndexRecommendation && (+ <>+ <div className="flex flex-col gap-y-2">+ <p className="text-sm">Query costs</p>+ <div className="border rounded-md flex flex-col bg-surface-100">+ <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={total_cost_before}+ after={total_cost_after}+ />+ <Collapsible_Shadcn_ open={showStartupCosts} onOpenChange={setShowStartupCosts}>+ <CollapsibleContent_Shadcn_ asChild className="pb-3">+ <QueryPanelScoreSection+ hideArrowMarkers+ className="border-t"+ name="Start up cost"+ description="An estimate of how long it will take to fetch the first row"+ before={startup_cost_before}+ after={startup_cost_after}+ />+ </CollapsibleContent_Shadcn_>+ <CollapsibleTrigger_Shadcn_ className="text-xs py-1.5 border-t text-foreground-light bg-studio w-full rounded-b-md">+ View {showStartupCosts ? 'less' : 'more'}+ </CollapsibleTrigger_Shadcn_>+ </Collapsible_Shadcn_>+ </div>+ </div>+ <div className="flex flex-col gap-y-2">+ <p className="text-sm">FAQ</p>+ <Accordion_Shadcn_ collapsible type="single" className="border rounded-md">+ <AccordionItem_Shadcn_ value="1">+ <AccordionTrigger className="px-4 py-3 text-sm font-normal text-foreground-light hover:text-foreground transition [&[data-state=open]]:text-foreground">+ What units are cost in?+ </AccordionTrigger>+ <AccordionContent_Shadcn_ className="px-4 text-foreground-light">+ Costs are in an arbitrary unit, and do not represent a unit of time. The units+ are anchored (by default) to a single sequential page read costing 1.0 units.+ They do, however, serve as a predictor of higher execution times.+ </AccordionContent_Shadcn_>+ </AccordionItem_Shadcn_>+ <AccordionItem_Shadcn_ value="2" className="border-b-0">+ <AccordionTrigger className="px-4 py-3 text-sm font-normal text-foreground-light hover:text-foreground transition [&[data-state=open]]:text-foreground">+ How should I prioritize start up and total cost?+ </AccordionTrigger>+ <AccordionContent_Shadcn_ className="px-4 text-foreground-light [&>div]:space-y-2">+ <p>This depends on the expected size of the result set from the query.</p>+ <p>+ For queries that return a small number or rows, the startup cost is more+ critical and minimizing startup cost can lead to faster response times,+ especially in interactive applications.+ </p>+ <p>+ For queries that return a large number of rows, the total cost becomes more+ important, and optimizing it will help in efficiently using resources and+ reducing overall query execution time.+ </p>+ </AccordionContent_Shadcn_>+ </AccordionItem_Shadcn_>+ </Accordion_Shadcn_>+ </div>+ </>+ )}+ </QueryPanelSection>++ {isIndexAdvisorAvailable && 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>+ <span className="text-xs text-foreground-light">+ This will run the SQL that is shown above+ </span>+ </div>+ <Button+ disabled={isExecuting}+ loading={isExecuting}+ type="primary"+ onClick={() => createIndex()}+ >+ Create index+ </Button>+ </div>+ )}+ </QueryPanelContainer>+ )+}diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/QueryPanel.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/QueryPanel.tsxnew file mode 100644index 00000000000..1613ccef24b--- /dev/null+++ b/apps/studio/components/interfaces/QueryPerformanceV2/QueryPanel.tsx@@ -0,0 +1,88 @@+import { InformationCircleIcon } from '@heroicons/react/16/solid'+import { ArrowDown, ArrowUp } from 'lucide-react'+import { PropsWithChildren } from 'react'+import { TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_, cn } from 'ui'++export const QueryPanelContainer = ({+ children,+ className,+}: PropsWithChildren<{ className?: string }>) => (+ <div className={cn('flex flex-col gap-y-6 py-4', className)}>{children}</div>+)++export const QueryPanelSection = ({+ children,+ className,+}: PropsWithChildren<{ className?: string }>) => (+ <div className={cn('px-5 flex flex-col gap-y-2', className)}>{children}</div>+)++export const QueryPanelScoreSection = ({+ className,+ name,+ description,+ before,+ after,+ hideArrowMarkers = false,+}: {+ className?: string+ name: string+ description: string+ before?: number+ after?: number+ hideArrowMarkers?: boolean+}) => (+ <div className={cn('py-4 px-4 flex', className)}>+ <div className="flex gap-x-2 w-48">+ <span className="text-sm">{name}</span>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild className="mt-1">+ <InformationCircleIcon className="transition text-foreground-muted w-3 h-3 data-[state=delayed-open]:text-foreground-light" />+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="top" className="w-52 text-center">+ {description}+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ </div>+ <div className="flex flex-col gap-y-1">+ <div className="flex gap-x-2 text-sm">+ <span className="text-foreground-light w-20">Currently:</span>+ <span+ className={cn(+ 'font-mono',+ before !== undefined && after !== undefined && before !== after+ ? 'text-foreground-light'+ : ''+ )}+ >+ {before}+ </span>+ </div>+ {before !== undefined && after !== undefined && before !== after && (+ <div className="flex items-center gap-x-2 text-sm">+ <span className="text-foreground-light w-20">With index:</span>+ <span className="font-mono">{after}</span>+ {before !== undefined && !hideArrowMarkers && (+ <div className="flex items-center gap-x-1">+ {after > before ? (+ <ArrowUp size={14} className="text-warning" />+ ) : (+ <ArrowDown size={14} className="text-brand" />+ )}+ {before !== 0 && (+ <span+ className={cn(+ 'font-mono tracking-tighter',+ after > before ? 'text-warning' : 'text-brand'+ )}+ >+ {(((before - after) / before) * 100).toFixed(2)}%+ </span>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ </div>+)diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformance.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformance.tsxindex 201e9eae327..1b3919b3de6 100644--- a/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformance.tsx+++ b/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformance.tsx@@ -116,8 +116,7 @@ export const QueryPerformance = ({key={tab.id}value={tab.id}className={cn(- 'group',- 'relative',+ '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%]',@@ -128,7 +127,7 @@ export const QueryPerformance = ({)}>{tab.id === page && (- <div className="absolute top-0 left-0 w-full h-[1px] bg-foreground"></div>+ <div className="absolute top-0 left-0 w-full h-[1px] bg-foreground" />)}<div className="flex items-center gap-x-2">diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformanceGrid.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformanceGrid.tsxindex f1bb109d4df..c67d120d7ea 100644--- a/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformanceGrid.tsx+++ b/apps/studio/components/interfaces/QueryPerformanceV2/QueryPerformanceGrid.tsx@@ -1,7 +1,7 @@import { ArrowDown, ArrowUp, TextSearch, X } from 'lucide-react'import { useRouter } from 'next/router'-import { useEffect, useState } from 'react'-import DataGrid, { Column } from 'react-data-grid'+import { useEffect, useRef, useState } from 'react'+import DataGrid, { Column, DataGridHandle, Row } from 'react-data-grid'import { useParams } from 'common'import { DbQueryHook } from 'hooks/analytics/useDbQuery'@@ -18,23 +18,23 @@ import {} from 'ui'import { GenericSkeletonLoader } from 'ui-patterns'import { QueryPerformanceSort } from '../Reports/Reports.queries'-import { IndexSuggestion } from './IndexSuggestion'import { QueryDetail } from './QueryDetail'+import { QueryIndexes } from './QueryIndexes'import {QUERY_PERFORMANCE_REPORTS,QUERY_PERFORMANCE_REPORT_TYPES,} from './QueryPerformance.constants'+import { useFlag } from 'hooks'interface QueryPerformanceGridProps {queryPerformanceQuery: DbQueryHook<any>}export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformanceGridProps) => {- // [Joshen] This will come in another PR to integrate index advisor- const showIndexSuggestions = false-const router = useRouter()- const { preset } = useParams()+ const gridRef = useRef<DataGridHandle>(null)+ const showIndexAdvisor = useFlag('indexAdvisor')+ const { preset, sort: urlSort, order, roles, search } = useParams()const { isLoading } = queryPerformanceQueryconst defaultSortValue = router.query.sort@@ -73,9 +73,16 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformancerenderCell: (props) => {const value = props.row?.[col.id]const isTime = col.name.includes('time')- const formattedValue = isTime ? `${value.toFixed(2)}ms` : String(value)+ const formattedValue = isTime+ ? `${Number(value.toFixed(2)).toLocaleString()}ms`+ : value.toLocaleString()return (- <div className="flex flex-col justify-center font-mono text-xs">+ <div+ className={cn(+ 'w-full flex flex-col justify-center font-mono text-xs',+ typeof value === 'number' ? 'text-right' : ''+ )}+ ><p>{formattedValue}</p>{isTime && <p className="text-foreground-lighter">{(value / 1000).toFixed(2)}s</p>}</div>@@ -85,6 +92,11 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformancereturn result})+ const selectedQuery =+ selectedRow !== undefined ? queryPerformanceQuery.data?.[selectedRow]['query'] : undefined+ const showIndexSuggestions =+ showIndexAdvisor && (selectedQuery ?? '').trim().toLowerCase().startsWith('select')+const onSortChange = (column: string) => {let updatedSort = undefined@@ -113,7 +125,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformanceuseEffect(() => {setSelectedRow(undefined)- }, [preset])+ }, [preset, search, roles, urlSort, order])return (<ResizablePanelGroup@@ -123,14 +135,11 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance><ResizablePanel defaultSize={1}><DataGrid+ ref={gridRef}style={{ height: '100%' }}className={cn('flex-1 flex-grow h-full')}rowHeight={44}headerRowHeight={36}- onSelectedCellChange={(props) => {- const { rowIdx } = props- if (rowIdx >= 0) setSelectedRow(rowIdx)- }}columns={columns}rows={queryPerformanceQuery?.data ?? []}rowClass={(_, idx) => {@@ -143,6 +152,24 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance].join(' ')}}renderers={{+ renderRow(idx, props) {+ return (+ <Row+ {...props}+ onClick={() => {+ if (typeof idx === 'number' && idx >= 0) {+ setSelectedRow(idx)+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })++ const selectedQuery = queryPerformanceQuery.data[idx]['query']+ if (!(selectedQuery ?? '').trim().toLowerCase().startsWith('select')) {+ setView('details')+ }+ }+ }}+ />+ )+ },noRowsFallback: isLoading ? (<div className="absolute top-14 px-6 w-full"><GenericSkeletonLoader />@@ -151,9 +178,9 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance<div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2"><TextSearch className="text-foreground-muted" strokeWidth={1} /><div className="text-center">- <p className="text-foreground">No queries detected yet</p>+ <p className="text-foreground">No queries detected</p><p className="text-foreground-light">- There are no queries actively running that meet the criteria+ There are no actively running queries that match the criteria</p></div></div>@@ -164,7 +191,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance{selectedRow !== undefined && (<><ResizableHandle withHandle />- <ResizablePanel defaultSize={20} maxSize={40} minSize={25} className="bg-studio border-t">+ <ResizablePanel defaultSize={30} maxSize={45} minSize={30} className="bg-studio border-t"><Buttontype="text"className="absolute top-3 right-3 px-1"@@ -172,34 +199,41 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformanceonClick={() => setSelectedRow(undefined)}/><Tabs_Shadcn_+ value={view}className="flex flex-col h-full"- defaultValue={view}onValueChange={(value: any) => setView(value)}>- <TabsList_Shadcn_ className="px-5 flex gap-x-4 h-12">- <TabsTrigger_Shadcn_ value="details" className="px-0 h-full">+ <TabsList_Shadcn_ className="px-5 flex gap-x-4 min-h-[46px]">+ <TabsTrigger_Shadcn_+ value="details"+ className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"+ >Query details</TabsTrigger_Shadcn_>{showIndexSuggestions && (- <TabsTrigger_Shadcn_ value="suggestion" className="px-0 h-full">- Index suggestion+ <TabsTrigger_Shadcn_+ value="suggestion"+ className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"+ >+ Indexes</TabsTrigger_Shadcn_>)}</TabsList_Shadcn_><TabsContent_Shadcn_value="details"- className="mt-0 pt-4 flex-grow min-h-0 overflow-y-auto"+ className="mt-0 flex-grow min-h-0 overflow-y-auto"><QueryDetailreportType={reportType}- selectedRow={queryPerformanceQuery.data[selectedRow]}+ selectedRow={queryPerformanceQuery.data?.[selectedRow]}+ onClickViewSuggestion={() => setView('suggestion')}/></TabsContent_Shadcn_><TabsContent_Shadcn_value="suggestion"- className="mt-0 pt-4 flex-grow min-h-0 overflow-y-auto"+ className="mt-0 flex-grow min-h-0 overflow-y-auto">- <IndexSuggestion />+ <QueryIndexes selectedRow={queryPerformanceQuery.data?.[selectedRow]} /></TabsContent_Shadcn_></Tabs_Shadcn_></ResizablePanel>diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/TextSearchPopover.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/TextSearchPopover.tsxindex 737faea9b3d..da9ad25e06b 100644--- a/apps/studio/components/interfaces/QueryPerformanceV2/TextSearchPopover.tsx+++ b/apps/studio/components/interfaces/QueryPerformanceV2/TextSearchPopover.tsx@@ -17,6 +17,11 @@ export const TextSearchPopover = ({ name, value = '', onSaveText }: TextSearchPoconst [open, setOpen] = useState(false)const [search, setSearch] = useState<string>(value)+ const applySearch = () => {+ onSaveText(search)+ setOpen(false)+ }+return (<Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}><PopoverTrigger_Shadcn_ asChild>@@ -40,6 +45,9 @@ export const TextSearchPopover = ({ name, value = '', onSaveText }: TextSearchPorows={4}className="text-xs font-mono tracking-tight"placeholder="Search for a query"+ onKeyDown={(event) => {+ if (event.metaKey && event.code === 'Enter') applySearch()+ }}/></div><div className="flex items-center justify-end gap-2 border-t border-overlay bg-surface-200 py-2 px-3">@@ -54,14 +62,8 @@ export const TextSearchPopover = ({ name, value = '', onSaveText }: TextSearchPo>Clear</Button>- <Button- type="primary"- onClick={() => {- onSaveText(search)- setOpen(false)- }}- >- Save+ <Button type="primary" onClick={() => applySearch()}>+ Apply search</Button></div></PopoverContent_Shadcn_>diff --git a/apps/studio/components/interfaces/Reports/Reports.queries.ts b/apps/studio/components/interfaces/Reports/Reports.queries.tsindex b85a21da920..012275a2e48 100644--- a/apps/studio/components/interfaces/Reports/Reports.queries.ts+++ b/apps/studio/components/interfaces/Reports/Reports.queries.ts@@ -32,19 +32,14 @@ export const useQueryPerformanceQuery = ({const whereSql = [roles !== undefined && roles.length > 0- ? `WHERE auth.rolname in (${roles.map((r) => `'${r}'`).join(', ')})`+ ? `auth.rolname in (${roles.map((r) => `'${r}'`).join(', ')})`: '',searchQuery.length > 0 ? `statements.query ~ '${searchQuery}'` : '',].filter((x) => x.length > 0).join(' OR ')- // [Joshen] TODO: Support ordering on more columns- // calls, total_time, prop_total_time, avg_rows, max_time, mean_time, min_time- // const orderBySql = orderBy === 'lat_asc' ? 'ORDER BY total_time asc' : 'ORDER BY total_time desc'const orderBySql = `ORDER BY ${orderBy.column} ${orderBy.order}`-- const sql = baseSQL.sql([], whereSql, orderBySql)-+ const sql = baseSQL.sql([], whereSql.length > 0 ? `WHERE ${whereSql}` : undefined, orderBySql)return useDbQuery(sql, undefined, whereSql, orderBySql)}diff --git a/apps/studio/data/database/index-advisor-enable-mutation.ts b/apps/studio/data/database/index-advisor-enable-mutation.tsindex f7775ef0d79..95419dd621b 100644--- a/apps/studio/data/database/index-advisor-enable-mutation.ts+++ b/apps/studio/data/database/index-advisor-enable-mutation.ts@@ -1,8 +1,9 @@-import { useMutation, UseMutationOptions } from '@tanstack/react-query'+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'react-hot-toast'import { executeSql } from 'data/sql/execute-sql-query'import type { ResponseError } from 'types'+import { sqlKeys } from 'data/sql/keys'// [Joshen] This is just temporary while we wait for Index Advisor to be baked into the image itself@@ -46,13 +47,13 @@ beginquery := trim(regexp_replace(regexp_replace(- regexp_replace(query,'\/\*.+\*\/', '', 'g'),- '--[^\r\n]*', ' ', 'g'),- '\s+', ' ', 'g')+ regexp_replace(query,'\\/\\*.+\\*\\/', '', 'g'),+ '--[^\\r\\n]*', ' ', 'g'),+ '\\s+', ' ', 'g'));-- Remove trailing semicolon- query := regexp_replace(query, ';\s*$', '');+ query := regexp_replace(query, ';\\s*$', '');begin-- Disallow multiple statements@@ -161,7 +162,7 @@ begin--raise notice '%', plan_final;- -- Identify referenced indexes in new plan+ -- Idenfity referenced indexes in new planexecute format('selectcoalesce(array_agg(hypopg_get_indexdef(indexrelid) order by indrelid, indkey::text), $i\${}$i$::text[])@@ -207,7 +208,12 @@ beginend;$$;`- const { result } = await executeSql({ projectRef, connectionString, sql })+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql,+ queryKey: ['enable-index-advisor'],+ })return result}@@ -222,10 +228,13 @@ export const useIndexAdvisorEnableMutation = ({UseMutationOptions<IndexAdvisorEnableData, ResponseError, IndexAdvisorEnableVariables>,'mutationFn'> = {}) => {+ const queryClient = useQueryClient()return useMutation<IndexAdvisorEnableData, ResponseError, IndexAdvisorEnableVariables>((vars) => enableIndexAdvisor(vars),{async onSuccess(data, variables, context) {+ const { projectRef } = variables+ queryClient.invalidateQueries(sqlKeys.query(projectRef, ['index-advisor-function-check']))await onSuccess?.(data, variables, context)},async onError(data, variables, context) {diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.tsindex dbaccaee8f9..605386f9616 100644--- a/apps/studio/data/database/keys.ts+++ b/apps/studio/data/database/keys.ts@@ -3,4 +3,8 @@ export const databaseKeys = {backups: (projectRef: string | undefined) => [projectRef, 'database', 'backups'] as const,poolingConfiguration: (projectRef: string | undefined) =>[projectRef, 'database', 'pooling-configuration'] as const,+ indexesFromQuery: (projectRef: string | undefined, query: string) =>+ ['projects', projectRef, 'indexes', { query }] as const,+ indexAdvisorFromQuery: (projectRef: string | undefined, query: string) =>+ ['projects', projectRef, 'index-advisor', { query }] as const,}diff --git a/apps/studio/data/database/retrieve-index-advisor-result-query.ts b/apps/studio/data/database/retrieve-index-advisor-result-query.tsnew file mode 100644index 00000000000..9dae39adb96--- /dev/null+++ b/apps/studio/data/database/retrieve-index-advisor-result-query.ts@@ -0,0 +1,59 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import { executeSql } from 'data/sql/execute-sql-query'+import type { ResponseError } from 'types'+import { databaseKeys } from './keys'++export type GetIndexAdvisorResultVariables = {+ projectRef?: string+ connectionString?: string+ query: string+}++export type GetIndexAdvisorResultResponse = {+ errors: string[]+ index_statements: string[]+ startup_cost_before: number+ startup_cost_after: number+ total_cost_before: number+ total_cost_after: number+}++export async function getIndexAdvisorResult({+ projectRef,+ connectionString,+ query,+}: GetIndexAdvisorResultVariables) {+ if (!projectRef) throw new Error('Project ref is required')++ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql: `select * from index_advisor('${query}');`,+ })+ return result[0] as GetIndexAdvisorResultResponse+}++export type GetIndexAdvisorResultData = Awaited<ReturnType<typeof getIndexAdvisorResult>>+export type GetIndexAdvisorResultError = ResponseError++export const useGetIndexAdvisorResult = <TData = GetIndexAdvisorResultData>(+ { projectRef, connectionString, query }: GetIndexAdvisorResultVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<GetIndexAdvisorResultData, GetIndexAdvisorResultError, TData> = {}+) =>+ useQuery<GetIndexAdvisorResultData, GetIndexAdvisorResultError, TData>(+ databaseKeys.indexAdvisorFromQuery(projectRef, query),+ () => getIndexAdvisorResult({ projectRef, connectionString, query }),+ {+ retry: false,+ enabled:+ enabled &&+ typeof projectRef !== 'undefined' &&+ typeof query !== 'undefined' &&+ (query.startsWith('select') || query.startsWith('SELECT')),+ ...options,+ }+ )diff --git a/apps/studio/data/database/retrieve-index-from-select-query.ts b/apps/studio/data/database/retrieve-index-from-select-query.tsnew file mode 100644index 00000000000..050b0aedd25--- /dev/null+++ b/apps/studio/data/database/retrieve-index-from-select-query.ts@@ -0,0 +1,118 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import { executeSql } from 'data/sql/execute-sql-query'+import type { ResponseError } from 'types'+import { databaseKeys } from './keys'++export type GetInvolvedIndexesFromSelectQueryVariables = {+ projectRef?: string+ connectionString?: string+ query: string+}++export type GetInvolvedIndexesFromSelectQueryResponse = {+ name: string+ schema: string+ table: string+}++// [Joshen] This is experimental - hence why i'm chucking a create or replace query like this here++export async function getInvolvedIndexesInSelectQuery({+ projectRef,+ connectionString,+ query,+}: GetInvolvedIndexesFromSelectQueryVariables) {+ if (!projectRef) throw new Error('Project ref is required')++ try {+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql: `+CREATE OR REPLACE FUNCTION pg_temp.explain_query(query TEXT) RETURNS JSONB AS $$+DECLARE+ explain_result JSONB;+ prepared_statement_name TEXT := 'query_to_explain';+ n_args INT;+BEGIN+ -- Disallow multiple statements+ IF query ILIKE '%;%' THEN+ RAISE EXCEPTION 'Query must not contain a semicolon';+ END IF;++ -- Construct the parameterized query+ EXECUTE 'PREPARE ' || prepared_statement_name || ' AS ' || query;++ -- Detect how many arguments are present in the prepared statement+ SELECT COALESCE(array_length(parameter_types, 1), 0)+ INTO n_args+ FROM pg_prepared_statements+ WHERE name = prepared_statement_name+ LIMIT 1;++ -- Construct the EXECUTE statement with parameters using dynamic SQL construction+ IF n_args > 0 THEN+ EXECUTE 'EXPLAIN (FORMAT JSON) EXECUTE ' || prepared_statement_name || '(' || quote_literal($1) || ')' INTO explain_result;+ ELSE+ EXECUTE 'EXPLAIN (FORMAT JSON) EXECUTE ' || prepared_statement_name INTO explain_result;+ END IF;++ -- Deallocate the prepared statement+ EXECUTE 'DEALLOCATE ' || prepared_statement_name;++ -- Return the explain result+ RETURN explain_result;+END;+$$ LANGUAGE plpgsql;+select pg_temp.explain_query('${query}') as plans;+`.trim(),+ })++ const involvedIndexes = result[0].plans+ .filter((plan: any) => 'Index Name' in plan['Plan'])+ .map((plan: any) => `'${plan['Plan']['Index Name']}'`)++ if (involvedIndexes.length === 0) return []++ const { result: indexResult } = await executeSql({+ projectRef,+ connectionString,+ sql: `select schemaname as schema, tablename as table, indexname as name from pg_indexes where indexname in (${involvedIndexes.join(', ')});`,+ })++ return indexResult as GetInvolvedIndexesFromSelectQueryResponse[]+ } catch (err) {+ return []+ }+}++export type GetInvolvedIndexesFromSelectQueryData = Awaited<+ ReturnType<typeof getInvolvedIndexesInSelectQuery>+>+export type GetInvolvedIndexesFromSelectQueryError = ResponseError++export const useGetIndexesFromSelectQuery = <TData = GetInvolvedIndexesFromSelectQueryData>(+ { projectRef, connectionString, query }: GetInvolvedIndexesFromSelectQueryVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<+ GetInvolvedIndexesFromSelectQueryData,+ GetInvolvedIndexesFromSelectQueryError,+ TData+ > = {}+) =>+ useQuery<GetInvolvedIndexesFromSelectQueryData, GetInvolvedIndexesFromSelectQueryError, TData>(+ databaseKeys.indexesFromQuery(projectRef, query),+ () => getInvolvedIndexesInSelectQuery({ projectRef, connectionString, query }),+ {+ retry: false,+ enabled:+ enabled &&+ typeof projectRef !== 'undefined' &&+ typeof query !== 'undefined' &&+ (query.startsWith('select') || query.startsWith('SELECT')),+ ...options,+ }+ )diff --git a/packages/ui/src/components/CodeBlock/CodeBlock.tsx b/packages/ui/src/components/CodeBlock/CodeBlock.tsxindex 8ef88dd2347..c21cc0890d1 100644--- a/packages/ui/src/components/CodeBlock/CodeBlock.tsx+++ b/packages/ui/src/components/CodeBlock/CodeBlock.tsx@@ -1,25 +1,23 @@-import { Children } from 'react'+import { Check, Copy } from 'lucide-react'+import { useTheme } from 'next-themes'+import { Children, ReactNode, useState } from 'react'import * as CopyToClipboard from 'react-copy-to-clipboard'import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'+import { Button, cn } from 'ui'import { monokaiCustomTheme } from './CodeBlock.utils'-import { Button, IconCheck, IconCopy, cn } from 'ui'-import js from 'react-syntax-highlighter/dist/cjs/languages/hljs/javascript'-import ts from 'react-syntax-highlighter/dist/cjs/languages/hljs/typescript'-import csharp from 'react-syntax-highlighter/dist/cjs/languages/hljs/csharp'-import py from 'react-syntax-highlighter/dist/cjs/languages/hljs/python'-import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql'import bash from 'react-syntax-highlighter/dist/cjs/languages/hljs/bash'+import csharp from 'react-syntax-highlighter/dist/cjs/languages/hljs/csharp'import dart from 'react-syntax-highlighter/dist/cjs/languages/hljs/dart'+import js from 'react-syntax-highlighter/dist/cjs/languages/hljs/javascript'import json from 'react-syntax-highlighter/dist/cjs/languages/hljs/json'import kotlin from 'react-syntax-highlighter/dist/cjs/languages/hljs/kotlin'--import { useState } from 'react'-import { useTheme } from 'next-themes'-import { Check, Copy } from 'lucide-react'+import py from 'react-syntax-highlighter/dist/cjs/languages/hljs/python'+import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql'+import ts from 'react-syntax-highlighter/dist/cjs/languages/hljs/typescript'export interface CodeBlockProps {- title?: string+ title?: ReactNodelanguage?: 'js' | 'jsx' | 'sql' | 'py' | 'bash' | 'ts' | 'dart' | 'json' | 'csharp' | 'kotlin'linesToHighlight?: number[]hideCopy?: boolean@@ -84,14 +82,14 @@ export const CodeBlock = ({const showLineNumbers = !hideLineNumbersreturn (- <>+ <div>{title && (- <div className="rounded-t-md bg-surface-100 py-2 px-4 border-b border-default text-blue-1100 font-sans">- {title.replace(/%20/g, ' ')}+ <div className="text-sm rounded-t-md bg-surface-100 py-2 px-4 border border-b-0 border-default font-sans">+ {title}</div>)}{className ? (- <div className="relative max-w-[90vw] md:max-w-none overflow-auto">+ <div className="group relative max-w-[90vw] md:max-w-none overflow-auto">{/* @ts-ignore */}<SyntaxHighlighterlanguage={lang}@@ -137,9 +135,9 @@ export const CodeBlock = ({{!hideCopy && (value || children) && className ? (<divclassName={[- 'absolute right-2',+ 'absolute right-2 top-2',+ 'opacity-0 group-hover:opacity-100 transition',`${isDarkTheme ? 'dark' : ''}`,- `${!title ? 'top-2' : 'top-[3.25rem]'}`,].join(' ')}>{/* //@@ -160,6 +158,6 @@ export const CodeBlock = ({) : (<code className={shortCodeBlockClasses}>{value || children}</code>)}- </>+ </div>)}