The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: move perf report and query perf report to database (#22423)
Jonathan Summers-Muirc9281487545a
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsxnew file mode 100644index 00000000000..8343086ccf9--- /dev/null+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx@@ -0,0 +1,145 @@+import { useRouter } from 'next/router'+import { useState } from 'react'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+ IconArrowDown,+ IconArrowUp,+ IconRefreshCw,+ IconSearch,+ Input,+} from 'ui'++export const QueryPerformanceFilterBar = ({+ isLoading,+ onRefreshClick,+}: {+ isLoading: boolean+ onRefreshClick: () => void+}) => {+ const router = useRouter()+ const defaultSearchQueryValue = router.query.search ? String(router.query.search) : ''+ const defaultSortByValue = router.query.sort ? String(router.query.sort) : 'lat_desc'+ const [searchInputVal, setSearchInputVal] = useState(defaultSearchQueryValue)+ const [sortByValue, setSortByValue] = useState(defaultSortByValue)++ function getSortButtonLabel() {+ const sort = router.query.sort as 'lat_desc' | 'lat_asc'++ if (sort === 'lat_desc') {+ return 'Sorted by latency - high to low'+ } else {+ return 'Sorted by latency - low to high'+ }+ }++ function onSortChange(sort: string) {+ setSortByValue(sort)+ router.push({+ ...router,+ query: {+ ...router.query,+ sort,+ },+ })+ }++ const ButtonIcon = sortByValue === 'lat_desc' ? IconArrowDown : IconArrowUp++ return (+ <>+ <div className="flex justify-between items-center">+ <form+ className="py-3 flex gap-4"+ id="log-panel-search"+ onSubmit={(e) => {+ e.preventDefault()+ const formData = new FormData(e.target as HTMLFormElement)+ const searchQuery = formData.get('search')++ if (!searchQuery || typeof searchQuery !== 'string') {+ // if user has deleted the search query, remove it from the url+ const { search, ...rest } = router.query+ router.push({+ ...router,+ query: {+ ...rest,+ },+ })+ return+ }++ router.push({+ ...router,+ query: {+ ...router.query,+ search: searchQuery,+ },+ })+ }}+ >+ <Input+ className="w-60 group"+ size="tiny"+ placeholder="Search roles or queries"+ name="search"+ value={searchInputVal}+ onChange={(e) => setSearchInputVal(e.target.value)}+ autoComplete="off"+ icon={+ <div className="text-foreground-lighter">+ <IconSearch size={14} />+ </div>+ }+ actions={+ searchInputVal !== '' && (+ <button className="mx-2 text-foreground-light hover:text-foreground">{'↲'}</button>+ )+ }+ />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button icon={<ButtonIcon />}>{getSortButtonLabel()}</Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-56">+ <DropdownMenuRadioGroup value={sortByValue} onValueChange={onSortChange}>+ <DropdownMenuRadioItem+ defaultChecked={router.query.sort === 'lat_desc'}+ value={'lat_desc'}+ >+ Sort by latency - high to low+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem+ value={'lat_asc'}+ defaultChecked={router.query.sort === 'lat_asc'}+ >+ Sort by latency - low to high+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ </form>+ <div>+ <Button+ type="default"+ size="tiny"+ onClick={onRefreshClick}+ disabled={isLoading ? true : false}+ icon={+ <IconRefreshCw+ size="tiny"+ className={`text-foreground-light ${isLoading ? 'animate-spin' : ''}`}+ />+ }+ >+ {isLoading ? 'Refreshing' : 'Refresh'}+ </Button>+ </div>+ </div>+ </>+ )+}diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceLoadingRow.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceLoadingRow.tsxnew file mode 100644index 00000000000..6bd24ccba31--- /dev/null+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceLoadingRow.tsx@@ -0,0 +1,17 @@+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'++export const QueryPerformanceLoadingRow = ({ colSpan }: { colSpan: number }) => {+ return (+ <>+ {Array(4)+ .fill('')+ .map((_, i) => (+ <tr key={'loading-' + { i }}>+ <td colSpan={colSpan}>+ <ShimmeringLoader />+ </td>+ </tr>+ ))}+ </>+ )+}diff --git a/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts b/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsindex 4f6f6f81c07..26af4befb0d 100644--- a/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts+++ b/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts@@ -91,6 +91,18 @@ export const generateDatabaseMenu = (url: `/project/${ref}/database/types`,items: [],},+ {+ name: 'Query Performance',+ key: 'query-performance',+ url: `/project/${ref}/database/query-performance`,+ items: [],+ },+ {+ name: 'Database Linter',+ key: 'linter',+ url: `/project/${ref}/database/linter`,+ items: [],+ },],},]diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsxindex ee465c45186..59c836c9f10 100644--- a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx+++ b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx@@ -1,41 +1,40 @@+import { ChevronDown, Edit2, Plus, Trash } from 'lucide-react'+import Link from 'next/link'+import { useRouter } from 'next/router'+import React from 'react'+import toast from 'react-hot-toast'+import { CreateReportModal } from 'components/interfaces/Reports/Reports.CreateReportModal'import { UpdateCustomReportModal } from 'components/interfaces/Reports/Reports.UpdateModal'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { useContentDeleteMutation } from 'data/content/content-delete-mutation'import { useContentInsertMutation } from 'data/content/content-insert-mutation'import { Content, useContentQuery } from 'data/content/content-query'import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'import { useIsFeatureEnabled, useSelectedProject } from 'hooks'-import { uuidv4 } from 'lib/helpers'-import Link from 'next/link'-import { useRouter } from 'next/router'-import React from 'react'-import toast from 'react-hot-toast'import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,Button,DropdownMenu,DropdownMenuContent,DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,- IconChevronDown,- IconEdit2,- IconPlus,- IconTrash,Menu,- Modal,cn,} from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'const ReportsMenu = () => {const router = useRouter()- const insertReport = useContentInsertMutation()+ const { id } = router.query+ const project = useSelectedProject()const deleteReport = useContentDeleteMutation()const updateReport = useContentUpsertMutation()+ const storageEnabled = useIsFeatureEnabled('project_storage:all')- const project = useSelectedProject()- const { id } = router.queryconst pageKey = (id || router.pathname.split('/')[4]) as stringconst ref = project?.ref ?? 'default'@@ -44,8 +43,6 @@ const ReportsMenu = () => {const [showUpdateReportModal, setShowUpdateReportModal] = React.useState(false)const [selectedReport, setSelectedReport] = React.useState<Content>()- const storageEnabled = useIsFeatureEnabled('project_storage:all')-const { data: content, isLoading } = useContentQuery(ref)function getReportMenuItems() {@@ -103,58 +100,10 @@ const ReportsMenu = () => {key: 'database',url: `/project/${ref}/reports/database`,},- {- name: 'Query Performance',- key: 'query-performance',- url: `/project/${ref}/reports/query-performance`,- },- {- name: 'Project Linter',- key: 'linter',- url: `/project/${ref}/reports/linter`,- },],},]- async function createCustomReport({ name, description }: { name: string; description?: string }) {- try {- if (!ref) return-- const res = await insertReport.mutateAsync({- projectRef: ref,- payload: {- id: uuidv4(),- type: 'report',- name,- description: description || '',- visibility: 'project',- content: {- schema_version: 1,- period_start: {- time_period: '7d',- date: '',- },- period_end: {- time_period: 'today',- date: '',- },- interval: '1d',- layout: [],- },- },- })- toast.success('New report created')-- const newReportId = res[0].id- setShowNewReportModal(false)- router.push(`/project/${ref}/reports/${newReportId}`)- } catch (error) {- toast.error(`Failed to create report. Check console for more details.`)- console.error(error)- }- }-return (<Menu type="pills" className="mt-6">{isLoading ? (@@ -164,7 +113,7 @@ const ReportsMenu = () => {<ShimmeringLoader className="w-1/2" /></div>) : (- <div className="flex flex-col px-2">+ <div className="flex flex-col px-2 gap-y-6"><div className="flex px-2"><Buttontype="default"@@ -172,13 +121,14 @@ const ReportsMenu = () => {onClick={() => {setShowNewReportModal(true)}}- icon={<IconPlus size="tiny" />}+ icon={<Plus size={12} />}>New custom report</Button></div>+{reportMenuItems.length > 0 ? (- <div className="mt-6">+ <div><Menu.Group title={'Your custom reports'} />{reportMenuItems.map((item, idx) => (<Link@@ -197,7 +147,7 @@ const ReportsMenu = () => {<Buttontype="text"className="px-1 opacity-50 hover:opacity-100"- icon={<IconChevronDown size="tiny" strokeWidth={2} />}+ icon={<ChevronDown size={12} strokeWidth={2} />}/></DropdownMenuTrigger><DropdownMenuContent align="start" className="w-52 *:space-x-2">@@ -208,7 +158,7 @@ const ReportsMenu = () => {setShowUpdateReportModal(true)}}>- <IconEdit2 size="tiny" />+ <Edit2 size={12} /><div>Rename</div></DropdownMenuItem><DropdownMenuSeparator />@@ -219,7 +169,7 @@ const ReportsMenu = () => {setDeleteModalOpen(true)}}>- <IconTrash size="tiny" />+ <Trash size={12} /><div>Delete</div></DropdownMenuItem></DropdownMenuContent>@@ -228,8 +178,9 @@ const ReportsMenu = () => {))}</div>) : null}- {menuItems.map((item, idx) => (- <div className="mt-6" key={item.key + '-menu-group'}>++ {menuItems.map((item) => (+ <div key={item.key + '-menu-group'}>{item.items ? (<><Menu.Group title={item.title} />@@ -255,6 +206,20 @@ const ReportsMenu = () => {) : null}</div>))}++ {/* [Joshen] Temp notice while we shift some pages on 040424 - can probably remove in 3 months perhaps */}+ <Alert_Shadcn_>+ <AlertTitle_Shadcn_ className="text-sm">+ Query Performance and Project Linter reports have been shifted+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="text-xs">+ <p className="mb-2">They can now be found in the menu under the database section.</p>+ <Button type="default" size="tiny" onClick={() => {}}>+ Head over to Database+ </Button>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+<UpdateCustomReportModalonSubmit={async (newVals) => {try {@@ -286,6 +251,7 @@ const ReportsMenu = () => {description: selectedReport?.description || '',}}/>+<ConfirmationModaltitle="Delete custom report"confirmLabel="Delete report"@@ -313,6 +279,7 @@ const ReportsMenu = () => {</div></div></ConfirmationModal>+<CreateReportModalvisible={showNewReportModal}onCancel={() => {diff --git a/apps/studio/next.config.js b/apps/studio/next.config.jsindex 0c33363bf66..69929944471 100644--- a/apps/studio/next.config.js+++ b/apps/studio/next.config.js@@ -344,6 +344,16 @@ const nextConfig = {destination: '/project/:ref/sql/new',permanent: true,},+ {+ permanent: true,+ source: '/project/:ref/reports/linter',+ destination: '/project/:ref/database/linter',+ },+ {+ permanent: true,+ source: '/project/:ref/reports/query-performance',+ destination: '/project/:ref/database/query-performance',+ },...(process.env.NEXT_PUBLIC_BASE_PATH?.length? [{diff --git a/apps/studio/pages/project/[ref]/reports/linter.tsx b/apps/studio/pages/project/[ref]/database/linter.tsxsimilarity index 95%rename from apps/studio/pages/project/[ref]/reports/linter.tsxrename to apps/studio/pages/project/[ref]/database/linter.tsxindex cef9facabf0..e09407b7bcc 100644--- a/apps/studio/pages/project/[ref]/reports/linter.tsx+++ b/apps/studio/pages/project/[ref]/database/linter.tsx@@ -5,7 +5,7 @@ import { useMemo, useState } from 'react'import { AccordionTrigger } from '@ui/components/shadcn/ui/accordion'import { FilterPopover } from 'components/interfaces/AuditLogs'import ReportLintsTableRow from 'components/interfaces/Reports/ReportLintsTableRow'-import { ReportsLayout } from 'components/layouts'+import { DatabaseLayout } from 'components/layouts'import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'import Table from 'components/to-be-cleaned/Table'import { useProjectLintsQuery } from 'data/lint/lint-query'@@ -61,9 +61,9 @@ const ProjectLints: NextPageWithLayout = () => {<ScaffoldSection><div className="col-span-12 flex items-center justify-between"><div className="flec flex-col gap-y-1">- <h3 className="text-xl text-foreground">Project Linter</h3>+ <h3 className="text-xl text-foreground">Database Linter</h3><div className="text-sm text-foreground-lighter">- Identify common schema problems in your project's database+ Identify common schema problems in your database</div></div></div>@@ -148,13 +148,13 @@ const ProjectLints: NextPageWithLayout = () => {{isLoading ? (<div className="flex items-center gap-x-2"><Loader className="animate-spin" size={12} />- <p className="text-foreground-light">Checking project for issues...</p>+ <p className="text-foreground-light">Checking database for issues...</p></div>) : (<div className="flex items-center gap-x-2"><Check size={12} /><p className="text-foreground-light">- No issues have been found for this project+ No issues have been found for this database</p></div>)}@@ -198,10 +198,10 @@ const ProjectLints: NextPageWithLayout = () => {{isLoading ? (<><Loader className="animate-spin" size={12} />- Checking for project issues+ Checking for database issues</>) : (- 'No issues have been found for this project'+ 'No issues have been found for this database')}</p></Table.td>@@ -225,6 +225,6 @@ const ProjectLints: NextPageWithLayout = () => {)}-ProjectLints.getLayout = (page) => <ReportsLayout title="Linter">{page}</ReportsLayout>+ProjectLints.getLayout = (page) => <DatabaseLayout title="Linter">{page}</DatabaseLayout>export default ProjectLintsdiff --git a/apps/studio/pages/project/[ref]/database/query-performance.tsx b/apps/studio/pages/project/[ref]/database/query-performance.tsxnew file mode 100644index 00000000000..11b6e735c6d--- /dev/null+++ b/apps/studio/pages/project/[ref]/database/query-performance.tsx@@ -0,0 +1,429 @@+import Link from 'next/link'+import { useRouter } from 'next/router'+import { useState } from 'react'+import ReactMarkdown from 'react-markdown'++import { useParams } from 'common'+import { QueryPerformanceFilterBar } from 'components/interfaces/QueryPerformance/QueryPerformanceFilterBar'+import { QueryPerformanceLoadingRow } from 'components/interfaces/QueryPerformance/QueryPerformanceLoadingRow'+import ReportHeader from 'components/interfaces/Reports/ReportHeader'+import ReportQueryPerformanceTableRow from 'components/interfaces/Reports/ReportQueryPerformanceTableRow'+import { PRESET_CONFIG } from 'components/interfaces/Reports/Reports.constants'+import { useQueryPerformanceQuery } from 'components/interfaces/Reports/Reports.queries'+import { Presets } from 'components/interfaces/Reports/Reports.types'+import { queriesFactory } from 'components/interfaces/Reports/Reports.utils'+import { DatabaseLayout } from 'components/layouts'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'+import Table from 'components/to-be-cleaned/Table'+import { executeSql } from 'data/sql/execute-sql-query'+import { useFlag } from 'hooks'+import type { NextPageWithLayout } from 'types'+import { Accordion, Button, IconAlertCircle, IconCheckCircle, Tabs } from 'ui'+import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'++type QueryPerformancePreset = 'time' | 'frequent' | 'slowest'++const QueryPerformanceReport: NextPageWithLayout = () => {+ const router = useRouter()+ const { ref: projectRef } = useParams()+ const { project } = useProjectContext()+ const [showResetgPgStatStatements, setShowResetgPgStatStatements] = useState(false)++ const tableIndexEfficiencyEnabled = useFlag('tableIndexEfficiency')+ const config = PRESET_CONFIG[Presets.QUERY_PERFORMANCE]+ const hooks = queriesFactory(config.queries, projectRef ?? 'default')+ const queryHitRate = hooks.queryHitRate()++ const orderBy = (router.query.sort as 'lat_desc' | 'lat_asc') || 'lat_desc'+ const searchQuery = (router.query.search as string) || ''+ const presetMap = {+ time: 'mostTimeConsuming',+ frequent: 'mostFrequentlyInvoked',+ slowest: 'slowestExecutionTime',+ } as const+ const preset = presetMap[router.query.preset as QueryPerformancePreset] || 'mostTimeConsuming'++ const queryPerformanceQuery = useQueryPerformanceQuery({+ searchQuery,+ orderBy,+ preset,+ })++ const isLoading = [queryPerformanceQuery.isLoading, queryHitRate.isLoading].every(+ (value) => value+ )++ const handleRefresh = async () => {+ queryPerformanceQuery.runQuery()+ queryHitRate.runQuery()+ }++ const checkAlert = (+ <div className="w-5 h-5 text-brand-1400 text-brand flex items-center justify-center">+ <IconCheckCircle strokeWidth={2} size={16} />+ </div>+ )+ const warnAlert = (+ <div className="w-6 h-6 text-yellow-900 flex items-center justify-center">+ <IconAlertCircle strokeWidth={2} size={16} />+ </div>+ )+ const dangerAlert = (+ <div className="w-6 h-6 text-red-900 flex items-center justify-center">+ <IconAlertCircle strokeWidth={2} size={16} />+ </div>+ )++ const indexHitRate = queryHitRate.data?.[0]?.ratio+ const tableHitRate = queryHitRate.data?.[1]?.ratio+ const showIndexWarning =+ indexHitRate && tableHitRate && (indexHitRate <= 0.99 || tableHitRate <= 0.99)++ const headerText = (+ <p className="whitespace-pre-wrap prose text-sm max-w-2xl text-foreground-light">+ Identify the queries that consume the most time and database resources.+ {'\n\n'}It relies on the <code>pg_stat_statements</code> table. Read more about{' '}+ <Link+ href="https://supabase.com/docs/guides/platform/performance#examining-query-performance"+ target="_blank"+ rel="noreferrer"+ >+ examining query performance+ </Link>+ .{'\n\n'}Consider resetting the analysis after optimizing any queries.+ </p>+ )++ const TimeConsumingHelperText = `This table lists queries ordered by their cumulative total execution time.++ It displays the total time a query has spent running and the proportion of total execution time the query has consumed.+`++ const MostFrequentHelperText = `This table lists queries in order of their execution count, providing insights into the most frequently executed queries.++ Pay attention to queries with high max_time or mean_time values that are called frequently, as they may benefit from optimization.+`++ const SlowestExecutionHelperText = `This table lists queries ordered by their maximum execution time. It shows outliers with high execution times. Queries with long execution times may benefit from optimization.++ Look for queries with high or mean execution times. These are often good candidates for optimization.+`+ const panelClassNames = 'text-sm max-w-none flex flex-col gap-8 py-4'+ const helperTextClassNames = 'prose text-sm max-w-2xl text-foreground-light'++ return (+ <ScaffoldContainer>+ <ScaffoldSection>+ <div className="col-span-12">+ <ReportHeader title="Query Performance" isLoading={isLoading} onRefresh={handleRefresh} />+ {tableIndexEfficiencyEnabled && (+ <Accordion+ openBehaviour="multiple"+ chevronAlign="right"+ className="border p-2 bg-surface-100 rounded"+ >+ <Accordion.Item+ header={+ <div className="flex flex-row gap-2 items-center p-2">+ <span className="text-xl">Index Efficiency</span>+ {showIndexWarning ? warnAlert : checkAlert}+ </div>+ }+ id="1"+ className="flex flex-row gap-8"+ >+ {!isLoading && queryHitRate && (+ <div>+ <div className="flex flex-row px-8 py-4 gap-8">+ <div className="w-1/2 bg-slate-200 rounded-md p-4">+ Index Hit Rate+ <div className="flex items-center gap-2">+ {indexHitRate >= 0.99+ ? checkAlert+ : indexHitRate >= 0.95+ ? warnAlert+ : dangerAlert}+ <div className="flex items-baseline">+ <span className="text-3xl">+ {queryHitRate?.data &&+ (queryHitRate?.data[0]?.ratio * 100).toFixed(2)}+ </span>+ <span className="text-xl">%</span>+ </div>+ </div>+ </div>++ <div className="w-1/2 bg-slate-200 rounded-md p-4">+ {queryHitRate?.data![1]?.name == 'table hit rate' && 'Table Hit Rate'}+ <div className="flex items-center gap-2">+ {tableHitRate >= 0.99+ ? checkAlert+ : tableHitRate >= 0.95+ ? warnAlert+ : dangerAlert}+ <div className="flex items-baseline">+ <span className="text-3xl">+ {queryHitRate?.data &&+ (queryHitRate?.data[1]?.ratio * 100).toFixed(2)}+ </span>+ <span className="text-xl">%</span>+ </div>+ </div>+ </div>+ </div>+ <div className="px-8 pt-4 m-0">+ <p className="text-foreground-light text-sm max-w-2xl">+ For best performance, ensure that the cache hit rate ratios above 99%.{' '}+ <br /> Consider upgrading to an instance with more memory if the ratios dip+ below 95%.+ </p>+ </div>+ </div>+ )}+ </Accordion.Item>+ </Accordion>+ )}++ {headerText}++ <div className="mb-8">+ <Button type="default" onClick={() => setShowResetgPgStatStatements(true)}>+ Reset analysis+ </Button>+ </div>++ <ConfirmModal+ danger+ visible={showResetgPgStatStatements}+ title="Reset query performance analysis"+ description={+ 'This will reset the `extensions.pg_stat_statements` table that is used to calculate query performance. This data will repopulate immediately after.'+ }+ buttonLabel="Clear table"+ buttonLoadingLabel="Deleting"+ onSelectCancel={() => setShowResetgPgStatStatements(false)}+ onSelectConfirm={async () => {+ try {+ await executeSql({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ sql: `SELECT pg_stat_statements_reset();`,+ })+ setShowResetgPgStatStatements(false)+ handleRefresh()+ } catch (error) {+ console.error(error)+ }+ }}+ />++ <div className="flex flex-col">+ <Tabs+ type="underlined"+ size="medium"+ onChange={(e: string) => {+ // To reset the search and sort query params when switching tabs+ const { sort, search, ...rest } = router.query+ router.push({+ ...router,+ query: {+ ...rest,+ preset: e,+ },+ })+ }}+ >+ <Tabs.Panel key={'time'} id="time" label="Most time consuming">+ <div className={panelClassNames}>+ <ReactMarkdown className={helperTextClassNames}>+ {TimeConsumingHelperText}+ </ReactMarkdown>+ <div className="thin-scrollbars max-w-full overflow-auto min-h-[800px]">+ <QueryPerformanceFilterBar+ onRefreshClick={handleRefresh}+ isLoading={isLoading}+ />+ <Table+ className="table-fixed"+ head={+ <>+ <Table.th className="text-ellipsis overflow-hidden">Role</Table.th>+ <Table.th className="w-[300px]">Query</Table.th>+ <Table.th className="text-right">Calls</Table.th>+ <Table.th className="text-right">Time Consumed</Table.th>+ <Table.th className="text-right">Total Time (Latency)</Table.th>+ </>+ }+ body={+ !queryPerformanceQuery.isLoading ? (+ queryPerformanceQuery?.data?.map((item, i) => {+ return (+ <ReportQueryPerformanceTableRow+ key={i + '-mosttimeconsumed'}+ sql={item.query}+ colSpan={5}+ >+ <Table.td className="truncate" title={item.rolname}>+ {item.rolname}+ </Table.td>+ <Table.td className="max-w-xs">+ <p className="font-mono line-clamp-2 text-xs">{item.query}</p>+ </Table.td>+ <Table.td className="truncate text-right">{item.calls}</Table.td>+ <Table.td className="truncate text-right">+ {item.prop_total_time}+ </Table.td>+ <Table.td className="truncate text-right">+ {item.total_time.toFixed(2)}ms+ </Table.td>+ </ReportQueryPerformanceTableRow>+ )+ })+ ) : (+ <QueryPerformanceLoadingRow colSpan={5} />+ )+ }+ />+ </div>+ </div>+ </Tabs.Panel>+ <Tabs.Panel key={'frequent'} id="frequent" label="Most frequent">+ <div className={panelClassNames}>+ <ReactMarkdown className={helperTextClassNames}>+ {MostFrequentHelperText}+ </ReactMarkdown>+ <div className="thin-scrollbars max-w-full overflow-auto min-h-[800px]">+ <QueryPerformanceFilterBar+ onRefreshClick={handleRefresh}+ isLoading={isLoading}+ />+ <Table+ head={+ <>+ <Table.th className="">Role</Table.th>+ <Table.th className="w-[300px]">Query</Table.th>+ <Table.th className="text-right">Avg. Roles</Table.th>+ <Table.th className="text-right">Calls</Table.th>+ <Table.th className="text-right">Max Time</Table.th>+ <Table.th className="text-right">Mean Time</Table.th>+ <Table.th className="text-right">Min Time</Table.th>+ <Table.th className="text-right">Total Time (Latency)</Table.th>+ </>+ }+ body={+ queryPerformanceQuery.isLoading ? (+ <QueryPerformanceLoadingRow colSpan={8} />+ ) : (+ queryPerformanceQuery.data?.map((item, i) => {+ return (+ <ReportQueryPerformanceTableRow+ key={i + '-mostfreq'}+ sql={item.query}+ colSpan={8}+ >+ <Table.td className="truncate" title={item.rolname}>+ {item.rolname}+ </Table.td>+ <Table.td className="min-w-xs">+ <p className="text-xs font-mono line-clamp-2">{item.query}</p>+ </Table.td>+ <Table.td className="truncate text-right">{item.avg_rows}</Table.td>+ <Table.td className="truncate text-right">{item.calls}</Table.td>+ <Table.td className="truncate text-right">+ {item.max_time?.toFixed(2)}ms+ </Table.td>+ <Table.td className="text-right truncate">+ {item.mean_time?.toFixed(2)}ms+ </Table.td>+ <Table.td className="text-right truncate">+ {item.min_time?.toFixed(2)}ms+ </Table.td>+ <Table.td className="text-right truncate">+ {item.total_time?.toFixed(2)}ms+ </Table.td>+ </ReportQueryPerformanceTableRow>+ )+ })+ )+ }+ />+ </div>+ </div>+ </Tabs.Panel>+ <Tabs.Panel key={'slowest'} id="slowest" label="Slowest execution time">+ <div className={panelClassNames}>+ <ReactMarkdown className={helperTextClassNames}>+ {SlowestExecutionHelperText}+ </ReactMarkdown>+ <div className="thin-scrollbars max-w-full overflow-auto min-h-[800px]">+ <QueryPerformanceFilterBar+ onRefreshClick={handleRefresh}+ isLoading={isLoading}+ />+ <Table+ head={+ <>+ <Table.th className="table-cell">Role</Table.th>+ <Table.th className="table-cell">Query</Table.th>+ <Table.th className="table-cell">Avg Rows</Table.th>+ <Table.th className="table-cell">Calls</Table.th>+ <Table.th className="table-cell">Max Time</Table.th>+ <Table.th className="table-cell">Mean Time</Table.th>+ <Table.th className="table-cell">Min Time</Table.th>+ <Table.th className="table-cell">Total Time (Latency)</Table.th>+ </>+ }+ body={+ queryPerformanceQuery.isLoading ? (+ <QueryPerformanceLoadingRow colSpan={8} />+ ) : (+ queryPerformanceQuery.data?.map((item, i) => {+ return (+ <ReportQueryPerformanceTableRow+ key={i + '-slowestexec'}+ sql={item.query}+ colSpan={8}+ >+ <Table.td className="truncate" title={item.rolname}>+ {item.rolname}+ </Table.td>+ <Table.td className="max-w-xs">+ <p className="font-mono line-clamp-2 text-xs">{item.query}</p>+ </Table.td>+ <Table.td className="truncate">{item.avg_rows}</Table.td>+ <Table.td className="truncate">{item.calls}</Table.td>+ <Table.td className="truncate">+ {item.max_time?.toFixed(2)}ms+ </Table.td>+ <Table.td className="truncate">+ {item.mean_time?.toFixed(2)}ms+ </Table.td>+ <Table.td className="truncate">+ {item.min_time?.toFixed(2)}ms+ </Table.td>+ <Table.td className="truncate">+ {item.total_time?.toFixed(2)}ms+ </Table.td>+ </ReportQueryPerformanceTableRow>+ )+ })+ )+ }+ />+ </div>+ </div>+ </Tabs.Panel>+ </Tabs>+ </div>+ </div>+ </ScaffoldSection>+ </ScaffoldContainer>+ )+}++QueryPerformanceReport.getLayout = (page) => (+ <DatabaseLayout title="Query performance">{page}</DatabaseLayout>+)++export default QueryPerformanceReportdiff --git a/apps/studio/pages/project/[ref]/reports/query-performance.tsx b/apps/studio/pages/project/[ref]/reports/query-performance.tsxdeleted file mode 100644index ac235d68aa5..00000000000--- a/apps/studio/pages/project/[ref]/reports/query-performance.tsx+++ /dev/null@@ -1,567 +0,0 @@-import { useParams } from 'common'-import Link from 'next/link'-import { useRouter } from 'next/router'-import { useState } from 'react'-import ReactMarkdown from 'react-markdown'-import {- Accordion,- Button,- DropdownMenu,- DropdownMenuContent,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuTrigger,- IconAlertCircle,- IconArrowDown,- IconArrowUp,- IconCheckCircle,- IconRefreshCw,- IconSearch,- Input,- Tabs,-} from 'ui'-import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'--import ReportHeader from 'components/interfaces/Reports/ReportHeader'-import ReportQueryPerformanceTableRow from 'components/interfaces/Reports/ReportQueryPerformanceTableRow'-import { PRESET_CONFIG } from 'components/interfaces/Reports/Reports.constants'-import { useQueryPerformanceQuery } from 'components/interfaces/Reports/Reports.queries'-import { Presets } from 'components/interfaces/Reports/Reports.types'-import { queriesFactory } from 'components/interfaces/Reports/Reports.utils'-import { ReportsLayout } from 'components/layouts'-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'-import Table from 'components/to-be-cleaned/Table'-import ShimmeringLoader from 'components/ui/ShimmeringLoader'-import { executeSql } from 'data/sql/execute-sql-query'-import { useFlag } from 'hooks'-import type { NextPageWithLayout } from 'types'--type QueryPerformancePreset = 'time' | 'frequent' | 'slowest'--const QueryPerformanceReport: NextPageWithLayout = () => {- const router = useRouter()- const { ref: projectRef } = useParams()- const { project } = useProjectContext()- const [showResetgPgStatStatements, setShowResetgPgStatStatements] = useState(false)-- const tableIndexEfficiencyEnabled = useFlag('tableIndexEfficiency')- const config = PRESET_CONFIG[Presets.QUERY_PERFORMANCE]- const hooks = queriesFactory(config.queries, projectRef ?? 'default')- const queryHitRate = hooks.queryHitRate()-- const orderBy = (router.query.sort as 'lat_desc' | 'lat_asc') || 'lat_desc'- const searchQuery = (router.query.search as string) || ''- const presetMap = {- time: 'mostTimeConsuming',- frequent: 'mostFrequentlyInvoked',- slowest: 'slowestExecutionTime',- } as const- const preset = presetMap[router.query.preset as QueryPerformancePreset] || 'mostTimeConsuming'-- const queryPerformanceQuery = useQueryPerformanceQuery({- searchQuery,- orderBy,- preset,- })-- const isLoading = [queryPerformanceQuery.isLoading, queryHitRate.isLoading].every(- (value) => value- )-- const handleRefresh = async () => {- queryPerformanceQuery.runQuery()- queryHitRate.runQuery()- }-- const checkAlert = (- <div className="w-5 h-5 text-brand-1400 text-brand flex items-center justify-center">- <IconCheckCircle strokeWidth={2} size={16} />- </div>- )- const warnAlert = (- <div className="w-6 h-6 text-yellow-900 flex items-center justify-center">- <IconAlertCircle strokeWidth={2} size={16} />- </div>- )- const dangerAlert = (- <div className="w-6 h-6 text-red-900 flex items-center justify-center">- <IconAlertCircle strokeWidth={2} size={16} />- </div>- )-- const indexHitRate = queryHitRate.data?.[0]?.ratio- const tableHitRate = queryHitRate.data?.[1]?.ratio- const showIndexWarning =- indexHitRate && tableHitRate && (indexHitRate <= 0.99 || tableHitRate <= 0.99)-- const headerText = (- <p className="whitespace-pre-wrap prose text-sm max-w-2xl text-foreground-light">- Identify the queries that consume the most time and database resources.- {'\n\n'}It relies on the <code>pg_stat_statements</code> table. Read more about{' '}- <Link- href="https://supabase.com/docs/guides/platform/performance#examining-query-performance"- target="_blank"- rel="noreferrer"- >- examining query performance- </Link>- .{'\n\n'}Consider resetting the analysis after optimizing any queries.- </p>- )-- const TimeConsumingHelperText = `This table lists queries ordered by their cumulative total execution time.-- It displays the total time a query has spent running and the proportion of total execution time the query has consumed.-`-- const MostFrequentHelperText = `This table lists queries in order of their execution count, providing insights into the most frequently executed queries.-- Pay attention to queries with high max_time or mean_time values that are called frequently, as they may benefit from optimization.-`-- const SlowestExecutionHelperText = `This table lists queries ordered by their maximum execution time. It shows outliers with high execution times. Queries with long execution times may benefit from optimization.-- Look for queries with high or mean execution times. These are often good candidates for optimization.-`- const panelClassNames = 'text-sm max-w-none flex flex-col gap-8 py-4'- const helperTextClassNames = 'prose text-sm max-w-2xl text-foreground-light'-- return (- <div className="p-4 py-3">- <ReportHeader title="Query Performance" isLoading={isLoading} onRefresh={handleRefresh} />- {tableIndexEfficiencyEnabled && (- <Accordion- openBehaviour="multiple"- chevronAlign="right"- className="border p-2 bg-surface-100 rounded"- >- <Accordion.Item- header={- <div className="flex flex-row gap-2 items-center p-2">- <span className="text-xl">Index Efficiency</span>- {showIndexWarning ? warnAlert : checkAlert}- </div>- }- id="1"- className="flex flex-row gap-8"- >- {!isLoading && queryHitRate && (- <div>- <div className="flex flex-row px-8 py-4 gap-8">- <div className="w-1/2 bg-slate-200 rounded-md p-4">- Index Hit Rate- <div className="flex items-center gap-2">- {indexHitRate >= 0.99- ? checkAlert- : indexHitRate >= 0.95- ? warnAlert- : dangerAlert}- <div className="flex items-baseline">- <span className="text-3xl">- {queryHitRate?.data && (queryHitRate?.data[0]?.ratio * 100).toFixed(2)}- </span>- <span className="text-xl">%</span>- </div>- </div>- </div>-- <div className="w-1/2 bg-slate-200 rounded-md p-4">- {queryHitRate?.data![1]?.name == 'table hit rate' && 'Table Hit Rate'}- <div className="flex items-center gap-2">- {tableHitRate >= 0.99- ? checkAlert- : tableHitRate >= 0.95- ? warnAlert- : dangerAlert}- <div className="flex items-baseline">- <span className="text-3xl">- {queryHitRate?.data && (queryHitRate?.data[1]?.ratio * 100).toFixed(2)}- </span>- <span className="text-xl">%</span>- </div>- </div>- </div>- </div>- <div className="px-8 pt-4 m-0">- <p className="text-foreground-light text-sm max-w-2xl">- For best performance, ensure that the cache hit rate ratios above 99%. <br />{' '}- Consider upgrading to an instance with more memory if the ratios dip below 95%.- </p>- </div>- </div>- )}- </Accordion.Item>- </Accordion>- )}-- {headerText}-- <div className="mb-8">- <Button type="default" onClick={() => setShowResetgPgStatStatements(true)}>- Reset analysis- </Button>- </div>-- <ConfirmModal- danger- visible={showResetgPgStatStatements}- title="Reset query performance analysis"- description={- 'This will reset the `extensions.pg_stat_statements` table that is used to calculate query performance. This data will repopulate immediately after.'- }- buttonLabel="Clear table"- buttonLoadingLabel="Deleting"- onSelectCancel={() => setShowResetgPgStatStatements(false)}- onSelectConfirm={async () => {- try {- await executeSql({- projectRef: project?.ref,- connectionString: project?.connectionString,- sql: `SELECT pg_stat_statements_reset();`,- })- setShowResetgPgStatStatements(false)- handleRefresh()- } catch (error) {- console.error(error)- }- }}- />-- <div className="flex flex-col">- <Tabs- type="underlined"- size="medium"- onChange={(e: string) => {- // To reset the search and sort query params when switching tabs- const { sort, search, ...rest } = router.query- router.push({- ...router,- query: {- ...rest,- preset: e,- },- })- }}- >- <Tabs.Panel key={'time'} id="time" label="Most time consuming">- <div className={panelClassNames}>- <ReactMarkdown className={helperTextClassNames}>- {TimeConsumingHelperText}- </ReactMarkdown>- <div className="thin-scrollbars max-w-full overflow-auto min-h-[800px]">- <QueryPerformanceFilterBar onRefreshClick={handleRefresh} isLoading={isLoading} />- <Table- className="table-fixed"- head={- <>- <Table.th className="text-ellipsis overflow-hidden">Role</Table.th>- <Table.th className="w-[300px]">Query</Table.th>- <Table.th className="text-right">Calls</Table.th>- <Table.th className="text-right">Time Consumed</Table.th>- <Table.th className="text-right">Total Time (Latency)</Table.th>- </>- }- body={- !queryPerformanceQuery.isLoading ? (- queryPerformanceQuery?.data?.map((item, i) => {- return (- <ReportQueryPerformanceTableRow- key={i + '-mosttimeconsumed'}- sql={item.query}- colSpan={5}- >- <Table.td className="truncate" title={item.rolname}>- {item.rolname}- </Table.td>- <Table.td className="max-w-xs">- <p className="font-mono line-clamp-2 text-xs">{item.query}</p>- </Table.td>- <Table.td className="truncate text-right">{item.calls}</Table.td>- <Table.td className="truncate text-right">- {item.prop_total_time}- </Table.td>- <Table.td className="truncate text-right">- {item.total_time.toFixed(2)}ms- </Table.td>- </ReportQueryPerformanceTableRow>- )- })- ) : (- <QueryPerformanceLoadingRow colSpan={5} />- )- }- />- </div>- </div>- </Tabs.Panel>- <Tabs.Panel key={'frequent'} id="frequent" label="Most frequent">- <div className={panelClassNames}>- <ReactMarkdown className={helperTextClassNames}>- {MostFrequentHelperText}- </ReactMarkdown>- <div className="thin-scrollbars max-w-full overflow-auto min-h-[800px]">- <QueryPerformanceFilterBar onRefreshClick={handleRefresh} isLoading={isLoading} />- <Table- head={- <>- <Table.th className="">Role</Table.th>- <Table.th className="w-[300px]">Query</Table.th>- <Table.th className="text-right">Avg. Roles</Table.th>- <Table.th className="text-right">Calls</Table.th>- <Table.th className="text-right">Max Time</Table.th>- <Table.th className="text-right">Mean Time</Table.th>- <Table.th className="text-right">Min Time</Table.th>- <Table.th className="text-right">Total Time (Latency)</Table.th>- </>- }- body={- queryPerformanceQuery.isLoading ? (- <QueryPerformanceLoadingRow colSpan={8} />- ) : (- queryPerformanceQuery.data?.map((item, i) => {- return (- <ReportQueryPerformanceTableRow- key={i + '-mostfreq'}- sql={item.query}- colSpan={8}- >- <Table.td className="truncate" title={item.rolname}>- {item.rolname}- </Table.td>- <Table.td className="min-w-xs">- <p className="text-xs font-mono line-clamp-2">{item.query}</p>- </Table.td>- <Table.td className="truncate text-right">{item.avg_rows}</Table.td>- <Table.td className="truncate text-right">{item.calls}</Table.td>- <Table.td className="truncate text-right">- {item.max_time?.toFixed(2)}ms- </Table.td>- <Table.td className="text-right truncate">- {item.mean_time?.toFixed(2)}ms- </Table.td>- <Table.td className="text-right truncate">- {item.min_time?.toFixed(2)}ms- </Table.td>- <Table.td className="text-right truncate">- {item.total_time?.toFixed(2)}ms- </Table.td>- </ReportQueryPerformanceTableRow>- )- })- )- }- />- </div>- </div>- </Tabs.Panel>- <Tabs.Panel key={'slowest'} id="slowest" label="Slowest execution time">- <div className={panelClassNames}>- <ReactMarkdown className={helperTextClassNames}>- {SlowestExecutionHelperText}- </ReactMarkdown>- <div className="thin-scrollbars max-w-full overflow-auto min-h-[800px]">- <QueryPerformanceFilterBar onRefreshClick={handleRefresh} isLoading={isLoading} />- <Table- head={- <>- <Table.th className="table-cell">Role</Table.th>- <Table.th className="table-cell">Query</Table.th>- <Table.th className="table-cell">Avg Rows</Table.th>- <Table.th className="table-cell">Calls</Table.th>- <Table.th className="table-cell">Max Time</Table.th>- <Table.th className="table-cell">Mean Time</Table.th>- <Table.th className="table-cell">Min Time</Table.th>- <Table.th className="table-cell">Total Time (Latency)</Table.th>- </>- }- body={- queryPerformanceQuery.isLoading ? (- <QueryPerformanceLoadingRow colSpan={8} />- ) : (- queryPerformanceQuery.data?.map((item, i) => {- return (- <ReportQueryPerformanceTableRow- key={i + '-slowestexec'}- sql={item.query}- colSpan={8}- >- <Table.td className="truncate" title={item.rolname}>- {item.rolname}- </Table.td>- <Table.td className="max-w-xs">- <p className="font-mono line-clamp-2 text-xs">{item.query}</p>- </Table.td>- <Table.td className="truncate">{item.avg_rows}</Table.td>- <Table.td className="truncate">{item.calls}</Table.td>- <Table.td className="truncate">{item.max_time?.toFixed(2)}ms</Table.td>- <Table.td className="truncate">{item.mean_time?.toFixed(2)}ms</Table.td>- <Table.td className="truncate">{item.min_time?.toFixed(2)}ms</Table.td>- <Table.td className="truncate">- {item.total_time?.toFixed(2)}ms- </Table.td>- </ReportQueryPerformanceTableRow>- )- })- )- }- />- </div>- </div>- </Tabs.Panel>- </Tabs>- </div>- </div>- )-}--QueryPerformanceReport.getLayout = (page) => (- <ReportsLayout title="Query performance">{page}</ReportsLayout>-)--export default QueryPerformanceReport--function QueryPerformanceFilterBar({- isLoading,- onRefreshClick,-}: {- isLoading: boolean- onRefreshClick: () => void-}) {- const router = useRouter()- const defaultSearchQueryValue = router.query.search ? String(router.query.search) : ''- const defaultSortByValue = router.query.sort ? String(router.query.sort) : 'lat_desc'- const [searchInputVal, setSearchInputVal] = useState(defaultSearchQueryValue)- const [sortByValue, setSortByValue] = useState(defaultSortByValue)-- function getSortButtonLabel() {- const sort = router.query.sort as 'lat_desc' | 'lat_asc'-- if (sort === 'lat_desc') {- return 'Sorted by latency - high to low'- } else {- return 'Sorted by latency - low to high'- }- }-- function onSortChange(sort: string) {- setSortByValue(sort)- router.push({- ...router,- query: {- ...router.query,- sort,- },- })- }-- const ButtonIcon = sortByValue === 'lat_desc' ? IconArrowDown : IconArrowUp-- return (- <>- <div className="flex justify-between items-center">- <form- className="py-3 flex gap-4"- id="log-panel-search"- onSubmit={(e) => {- e.preventDefault()- const formData = new FormData(e.target as HTMLFormElement)- const searchQuery = formData.get('search')-- if (!searchQuery || typeof searchQuery !== 'string') {- // if user has deleted the search query, remove it from the url- const { search, ...rest } = router.query- router.push({- ...router,- query: {- ...rest,- },- })- return- }-- router.push({- ...router,- query: {- ...router.query,- search: searchQuery,- },- })- }}- >- <Input- className="w-60 group"- size="tiny"- placeholder="Search roles or queries"- name="search"- value={searchInputVal}- onChange={(e) => setSearchInputVal(e.target.value)}- autoComplete="off"- icon={- <div className="text-foreground-lighter">- <IconSearch size={14} />- </div>- }- actions={- searchInputVal !== '' && (- <button className="mx-2 text-foreground-light hover:text-foreground">{'↲'}</button>- )- }- />- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button icon={<ButtonIcon />}>{getSortButtonLabel()}</Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="w-56">- <DropdownMenuRadioGroup value={sortByValue} onValueChange={onSortChange}>- <DropdownMenuRadioItem- defaultChecked={router.query.sort === 'lat_desc'}- value={'lat_desc'}- >- Sort by latency - high to low- </DropdownMenuRadioItem>- <DropdownMenuRadioItem- value={'lat_asc'}- defaultChecked={router.query.sort === 'lat_asc'}- >- Sort by latency - low to high- </DropdownMenuRadioItem>- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- </form>- <div>- <Button- type="default"- size="tiny"- onClick={onRefreshClick}- disabled={isLoading ? true : false}- icon={- <IconRefreshCw- size="tiny"- className={`text-foreground-light ${isLoading ? 'animate-spin' : ''}`}- />- }- >- {isLoading ? 'Refreshing' : 'Refresh'}- </Button>- </div>- </div>- </>- )-}--function QueryPerformanceLoadingRow({ colSpan }: { colSpan: number }) {- return (- <>- {Array(4)- .fill('')- .map((_, i) => (- <tr key={'loading-' + { i }}>- <td colSpan={colSpan}>- <ShimmeringLoader />- </td>- </tr>- ))}- </>- )-}