Skip to content

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

fix(policy editor): reduce number of table role access queries (#39601)

Charis9c4919948a90
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
index 47f460e5527..b8d9c8f3db4 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
@@ -4,7 +4,7 @@ import { noop } from 'lodash'
import AlertError from 'components/ui/AlertError'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
import { useDatabasePoliciesQuery } from 'data/database-policies/database-policies-query'
-import { useTableRolesAccessQuery } from 'data/tables/table-roles-access-query'
+import { useTablesRolesAccessQuery } from 'data/tables/tables-roles-access-query'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import {
Alert_Shadcn_,
@@ -65,13 +65,13 @@ export const PolicyTableRow = ({
const isRLSEnabled = table.rls_enabled
const isTableExposedThroughAPI = exposedSchemas.includes(table.schema)
- const { data: roles = [] } = useTableRolesAccessQuery({
+ const { data: tablesWithAnonAuthAccess = new Set() } = useTablesRolesAccessQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
schema: table.schema,
- table: table.name,
})
- const hasAnonAuthenticatedRolesAccess = roles.length !== 0
+
+ const hasAnonAuthenticatedRolesAccess = tablesWithAnonAuthAccess.has(table.name)
const isPubliclyReadableWritable =
!isRLSEnabled && isTableExposedThroughAPI && hasAnonAuthenticatedRolesAccess
diff --git a/apps/studio/data/tables/keys.ts b/apps/studio/data/tables/keys.ts
index ae12de36996..7eb0142fed4 100644
--- a/apps/studio/data/tables/keys.ts
+++ b/apps/studio/data/tables/keys.ts
@@ -3,10 +3,10 @@ export const tableKeys = {
['projects', projectRef, 'tables', schema, includeColumns].filter(Boolean),
retrieve: (projectRef: string | undefined, name: string, schema: string) =>
['projects', projectRef, 'tables', schema, name].filter(Boolean),
- rolesAccess: (projectRef: string | undefined, schema: string, table: string) => [
+ rolesAccess: (projectRef: string | undefined, schema: string) => [
'projects',
projectRef,
'roles-access',
- { schema, table },
+ { schema },
],
}
diff --git a/apps/studio/data/tables/table-roles-access-query.ts b/apps/studio/data/tables/table-roles-access-query.ts
deleted file mode 100644
index d47f2a04877..00000000000
--- a/apps/studio/data/tables/table-roles-access-query.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useQuery, UseQueryOptions } from '@tanstack/react-query'
-import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
-import { tableKeys } from './keys'
-
-type TableRolesAccessArgs = {
- schema: string
- table: string
-}
-
-/**
- * [Joshen] Specifically just checking for anon and authenticated roles since this is
- * just to verify if the table is exposed via the Supabase API
- */
-export const getTableRolesAccessSql = ({ schema, table }: TableRolesAccessArgs) => {
- const sql = /* SQL */ `
-SELECT grantee, privilege_type
-FROM information_schema.role_table_grants
-WHERE table_schema = '${schema}'
- AND table_name = '${table}'
- AND grantee IN ('anon', 'authenticated');
-`.trim()
-
- return sql
-}
-
-export type TableRolesAccessVariables = TableRolesAccessArgs & {
- projectRef?: string
- connectionString?: string | null
-}
-
-export async function getTableRolesAccess(
- { schema, table, projectRef, connectionString }: TableRolesAccessVariables,
- signal?: AbortSignal
-) {
- if (!schema) {
- throw new Error('schema is required')
- }
-
- const sql = getTableRolesAccessSql({ schema, table })
-
- const { result } = (await executeSql(
- { projectRef, connectionString, sql, queryKey: ['TableRolesAccess', schema] },
- signal
- )) as { result: { grantee: string; privilege_type: string }[] }
-
- const res = []
- if (result.some((x) => x.grantee === 'anon')) res.push('anon')
- if (result.some((x) => x.grantee === 'authenticated')) res.push('authenticated')
-
- return res
-}
-
-export type TableRolesAccessData = Awaited<ReturnType<typeof getTableRolesAccess>>
-export type TableRolesAccessError = ExecuteSqlError
-
-export const useTableRolesAccessQuery = <TData = TableRolesAccessData>(
- { projectRef, connectionString, schema, table }: TableRolesAccessVariables,
- {
- enabled = true,
- ...options
- }: UseQueryOptions<TableRolesAccessData, TableRolesAccessError, TData> = {}
-) =>
- useQuery<TableRolesAccessData, TableRolesAccessError, TData>(
- tableKeys.rolesAccess(projectRef, schema, table),
- ({ signal }) => getTableRolesAccess({ projectRef, connectionString, schema, table }, signal),
- {
- enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined',
- ...options,
- }
- )
diff --git a/apps/studio/data/tables/tables-roles-access-query.ts b/apps/studio/data/tables/tables-roles-access-query.ts
new file mode 100644
index 00000000000..70bd5e0fc2a
--- /dev/null
+++ b/apps/studio/data/tables/tables-roles-access-query.ts
@@ -0,0 +1,52 @@
+import { getTablesWithAnonAuthenticatedAccessSQL } from '@supabase/pg-meta/src/sql/studio/check-tables-anon-authenticated-access'
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+
+import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
+import { tableKeys } from './keys'
+
+type TablesRolesAccessArgs = {
+ schema: string
+}
+
+export type TablesRolesAccessVariables = TablesRolesAccessArgs & {
+ projectRef?: string
+ connectionString?: string | null
+}
+
+export async function getTablesWithAnonAuthenticatedAccess(
+ { schema, projectRef, connectionString }: TablesRolesAccessVariables,
+ signal?: AbortSignal
+) {
+ if (!schema) throw new Error('schema is required')
+
+ const sql = getTablesWithAnonAuthenticatedAccessSQL({ schema })
+
+ const { result } = (await executeSql(
+ { projectRef, connectionString, sql, queryKey: ['TablesRolesAccess', schema] },
+ signal
+ )) as { result: { table_name: string }[] }
+
+ return new Set(result.map((r) => r.table_name))
+}
+
+export type TablesRolesAccessData = Awaited<ReturnType<typeof getTablesWithAnonAuthenticatedAccess>>
+export type TablesRolesAccessError = ExecuteSqlError
+
+export const useTablesRolesAccessQuery = <TData = TablesRolesAccessData>(
+ { projectRef, connectionString, schema }: TablesRolesAccessVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<TablesRolesAccessData, TablesRolesAccessError, TData> = {}
+) =>
+ useQuery<TablesRolesAccessData, TablesRolesAccessError, TData>({
+ queryKey: tableKeys.rolesAccess(projectRef, schema),
+ queryFn: ({ signal }) =>
+ getTablesWithAnonAuthenticatedAccess({ projectRef, connectionString, schema }, signal),
+ enabled:
+ enabled &&
+ typeof projectRef !== 'undefined' &&
+ typeof schema !== 'undefined' &&
+ !!connectionString,
+ ...options,
+ })
diff --git a/packages/pg-meta/src/sql/studio/check-tables-anon-authenticated-access.ts b/packages/pg-meta/src/sql/studio/check-tables-anon-authenticated-access.ts
new file mode 100644
index 00000000000..ceaf86c7fa5
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/check-tables-anon-authenticated-access.ts
@@ -0,0 +1,20 @@
+/**
+ * Given a schema name, list all the tables in that schema which have access
+ * granted to either the "anon" or "authenticated" role
+ */
+export const getTablesWithAnonAuthenticatedAccessSQL = ({ schema }: { schema: string }) =>
+ /* SQL */ `
+SELECT c.relname AS table_name
+FROM pg_catalog.pg_class AS c
+JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
+WHERE n.nspname = '${schema}'
+ AND c.relkind IN ('r','p') -- table, partitioned table
+ AND EXISTS (
+ SELECT 1
+ FROM pg_catalog.aclexplode(COALESCE(c.relacl, '{}'::aclitem[])) AS a
+ JOIN pg_catalog.pg_roles r ON r.oid = a.grantee
+ WHERE r.rolname IN ('anon','authenticated')
+ )
+;
+`.trim()
+