The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/switch index advisor installation to db extension (#22773)
Joshen Lim05eac4af5105
diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/IndexAdvisorDisabledState.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/IndexAdvisorDisabledState.tsxindex 8f277142a18..f25c2cf93ce 100644--- a/apps/studio/components/interfaces/QueryPerformanceV2/IndexAdvisorDisabledState.tsx+++ b/apps/studio/components/interfaces/QueryPerformanceV2/IndexAdvisorDisabledState.tsx@@ -3,23 +3,23 @@ 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'+import Link from 'next/link'+import { useParams } from 'common'export const IndexAdvisorDisabledState = () => {+ const { ref } = useParams()const { project } = useProjectContext()const { data: extensions } = useDatabaseExtensionsQuery({projectRef: project?.ref,connectionString: project?.connectionString,})const hypopgExtension = (extensions ?? []).find((ext) => ext.name === 'hypopg')+ const indexAdvisorExtension = (extensions ?? []).find((ext) => ext.name === 'index_advisor')const { mutateAsync: enableExtension, isLoading: isEnablingExtension } =useDatabaseExtensionEnableMutation()- const { mutateAsync: enableIndexAdvisor, isLoading: isEnablingIndexAdvisor } =- useIndexAdvisorEnableMutation()- const isEnabling = isEnablingExtension || isEnablingIndexAdvisorconst onEnableIndexAdvisor = async () => {if (project === undefined) return console.error('Project is required')@@ -32,33 +32,56 @@ export const IndexAdvisorDisabledState = () => {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,- })+ if (indexAdvisorExtension?.installed_version === null) {+ await enableExtension({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ name: indexAdvisorExtension.name,+ schema: indexAdvisorExtension?.schema ?? 'extensions',+ version: indexAdvisorExtension.default_version,+ })+ }}return (- <Alert_Shadcn_>+ <Alert_Shadcn_ className="mb-6"><AlertTitle_Shadcn_>- Get index suggestions to improve your query performance+ <Markdown+ className="text-foreground"+ content={+ indexAdvisorExtension === undefined+ ? 'Newer version of Postgres required'+ : 'Postgres extensions `index_advisor` and `hypopg` required'+ }+ /></AlertTitle_Shadcn_><AlertDescription_Shadcn_>- <Markdown content="The `index_advisor` extension can help in recommending database indexes to reduce the costs of your query." />+ <Markdown+ content={+ indexAdvisorExtension === 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.'+ }+ /></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 />}>+ {indexAdvisorExtension === undefined ? (+ <Button asChild type="default">+ <Link href={`/project/${ref}/settings/infrastructure`}>Upgrade Postgres version</Link>+ </Button>+ ) : (+ <Button+ type="default"+ disabled={isEnablingExtension}+ loading={isEnablingExtension}+ onClick={() => onEnableIndexAdvisor()}+ >+ Enable extensions+ </Button>+ )}+ <Button asChild type="outline" icon={<ExternalLink />}><atarget="_blank"rel="noreferrer"diff --git a/apps/studio/components/interfaces/QueryPerformanceV2/QueryIndexes.tsx b/apps/studio/components/interfaces/QueryPerformanceV2/QueryIndexes.tsxindex 1af555dd169..139ed61b913 100644--- a/apps/studio/components/interfaces/QueryPerformanceV2/QueryIndexes.tsx+++ b/apps/studio/components/interfaces/QueryPerformanceV2/QueryIndexes.tsx@@ -9,7 +9,6 @@ import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-eximport { 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_,@@ -51,21 +50,16 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {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 || isLoadingExtensionsconst hypopgExtension = (extensions ?? []).find((ext) => ext.name === 'hypopg')+ const indexAdvisorExtension = (extensions ?? []).find((ext) => ext.name === 'index_advisor')const isIndexAdvisorAvailable =- (indexAdvisorExt?.result ?? []).length > 0 &&+ indexAdvisorExtension !== undefined &&+ indexAdvisorExtension.installed_version !== null &&hypopgExtension !== undefined &&hypopgExtension.installed_version !== null@@ -165,7 +159,7 @@ export const QueryIndexes = ({ selectedRow }: QueryIndexesProps) => {<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 ? (+ {isLoadingExtensions ? (<GenericSkeletonLoader />) : !isIndexAdvisorAvailable ? (<IndexAdvisorDisabledState />diff --git a/apps/studio/data/database/index-advisor-enable-mutation.ts b/apps/studio/data/database/index-advisor-enable-mutation.tsdeleted file mode 100644index 95419dd621b..00000000000--- a/apps/studio/data/database/index-advisor-enable-mutation.ts+++ /dev/null@@ -1,250 +0,0 @@-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--export type IndexAdvisorEnableVariables = {- projectRef: string- connectionString?: string-}--export async function enableIndexAdvisor({- projectRef,- connectionString,-}: IndexAdvisorEnableVariables) {- const sql = `-create or replace function index_advisor(- query text-)- returns table (- startup_cost_before jsonb,- startup_cost_after jsonb,- total_cost_before jsonb,- total_cost_after jsonb,- index_statements text[],- errors text[]- )- volatile- language plpgsql- as $$-declare- n_args int;- prepared_statement_name text = 'index_advisor_working_statement';- hypopg_schema_name text = (select extnamespace::regnamespace::text from pg_extension where extname = 'hypopg');- explain_plan_statement text;- error_message text;- rec record;- plan_initial jsonb;- plan_final jsonb;- statements text[] = '{}';-begin-- -- Remove comment lines (its common that they contain semicolons)- query := trim(- regexp_replace(- regexp_replace(- regexp_replace(query,'\\/\\*.+\\*\\/', '', 'g'),- '--[^\\r\\n]*', ' ', 'g'),- '\\s+', ' ', 'g')- );-- -- Remove trailing semicolon- query := regexp_replace(query, ';\\s*$', '');-- begin- -- Disallow multiple statements- if query ilike '%;%' then- raise exception 'Query must not contain a semicolon';- end if;-- -- Hack to support PostgREST because the prepared statement for args incorrectly defaults to text- query := replace(query, 'WITH pgrst_payload AS (SELECT $1 AS json_data)', 'WITH pgrst_payload AS (SELECT $1::json AS json_data)');-- -- Create a prepared statement for the given query- deallocate all;- execute format('prepare %I as %s', prepared_statement_name, query);-- -- Detect how many arguments are present in the prepared statement- n_args = (- select- coalesce(array_length(parameter_types, 1), 0)- from- pg_prepared_statements- where- name = prepared_statement_name- limit- 1- );-- -- Create a SQL statement that can be executed to collect the explain plan- explain_plan_statement = format(- 'set local plan_cache_mode = force_generic_plan; explain (format json) execute %I%s',- --'explain (format json) execute %I%s',- prepared_statement_name,- case- when n_args = 0 then ''- else format(- '(%s)', array_to_string(array_fill('null'::text, array[n_args]), ',')- )- end- );-- -- Store the query plan before any new indexes- execute explain_plan_statement into plan_initial;-- -- Create possible indexes- for rec in (- with extension_regclass as (- select- distinct objid as oid- from- pg_catalog.pg_depend- where- deptype = 'e'- )- select- pc.relnamespace::regnamespace::text as schema_name,- pc.relname as table_name,- pa.attname as column_name,- format(- 'select %I.hypopg_create_index($i$create index on %I.%I(%I)$i$)',- hypopg_schema_name,- pc.relnamespace::regnamespace::text,- pc.relname,- pa.attname- ) hypopg_statement- from- pg_catalog.pg_class pc- join pg_catalog.pg_attribute pa- on pc.oid = pa.attrelid- left join extension_regclass er- on pc.oid = er.oid- left join pg_catalog.pg_index pi- on pc.oid = pi.indrelid- and (select array_agg(x) from unnest(pi.indkey) v(x)) = array[pa.attnum]- and pi.indexprs is null -- ignore expression indexes- and pi.indpred is null -- ignore partial indexes- where- pc.relnamespace::regnamespace::text not in ( -- ignore schema list- 'pg_catalog', 'pg_toast', 'information_schema'- )- and er.oid is null -- ignore entities owned by extensions- and pc.relkind in ('r', 'm') -- regular tables, and materialized views- and pc.relpersistence = 'p' -- permanent tables (not unlogged or temporary)- and pa.attnum > 0- and not pa.attisdropped- and pi.indrelid is null- and pa.atttypid in (20,16,1082,1184,1114,701,23,21,700,1083,2950,1700,25,18,1042,1043)- )- loop- -- Create the hypothetical index- execute rec.hypopg_statement;- end loop;-- /*- for rec in select * from hypopg()- loop- raise notice '%', rec;- end loop;- */-- -- Create a prepared statement for the given query- -- The original prepared statement MUST be dropped because its plan is cached- execute format('deallocate %I', prepared_statement_name);- execute format('prepare %I as %s', prepared_statement_name, query);-- -- Store the query plan after new indexes- execute explain_plan_statement into plan_final;-- --raise notice '%', plan_final;-- -- Idenfity referenced indexes in new plan- execute format(- 'select- coalesce(array_agg(hypopg_get_indexdef(indexrelid) order by indrelid, indkey::text), $i\${}$i$::text[])- from- %I.hypopg()- where- %s ilike ($i$%%$i$ || indexname || $i$%%$i$)- ',- hypopg_schema_name,- quote_literal(plan_final)::text- ) into statements;-- -- Reset all hypothetical indexes- perform hypopg_reset();-- -- Reset prepared statements- deallocate all;-- return query values (- (plan_initial -> 0 -> 'Plan' -> 'Startup Cost'),- (plan_final -> 0 -> 'Plan' -> 'Startup Cost'),- (plan_initial -> 0 -> 'Plan' -> 'Total Cost'),- (plan_final -> 0 -> 'Plan' -> 'Total Cost'),- statements::text[],- array[]::text[]- );- return;-- exception when others then- get stacked diagnostics error_message = MESSAGE_TEXT;-- return query values (- null::jsonb,- null::jsonb,- null::jsonb,- null::jsonb,- array[]::text[],- array[error_message]::text[]- );- return;- end;--end;-$$;-`- const { result } = await executeSql({- projectRef,- connectionString,- sql,- queryKey: ['enable-index-advisor'],- })-- return result-}--type IndexAdvisorEnableData = Awaited<ReturnType<typeof enableIndexAdvisor>>--export const useIndexAdvisorEnableMutation = ({- onSuccess,- onError,- ...options-}: Omit<- 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) {- if (onError === undefined) {- toast.error(`Failed to enable index advisor: ${data.message}`)- } else {- onError(data, variables, context)- }- },- ...options,- }- )-}