The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/shift manual queries into pg meta 04 (#43956)
Joshen Lim98b1b79909d9
diff --git a/apps/studio/components/interfaces/Integrations/Vault/Secrets/AddNewSecretModal.tsx b/apps/studio/components/interfaces/Integrations/Vault/Secrets/AddNewSecretModal.tsxindex 208ade316f4..d8ae04695e1 100644--- a/apps/studio/components/interfaces/Integrations/Vault/Secrets/AddNewSecretModal.tsx+++ b/apps/studio/components/interfaces/Integrations/Vault/Secrets/AddNewSecretModal.tsx@@ -36,8 +36,6 @@ export const AddNewSecretModal = () => {setSubmitting(true)try {- setSubmitting(true)-await addSecret({projectRef: project.ref,connectionString: project?.connectionString,@@ -83,6 +81,7 @@ export const AddNewSecretModal = () => {<div className="mr-1"><Buttontype="default"+ className="w-7"icon={showSecretValue ? <EyeOff /> : <Eye />}onClick={() => setShowSecretValue(!showSecretValue)}/>diff --git a/apps/studio/components/interfaces/Integrations/Vault/Secrets/DeleteSecretModal.tsx b/apps/studio/components/interfaces/Integrations/Vault/Secrets/DeleteSecretModal.tsxindex 856fbf371b4..397b3d1d5b0 100644--- a/apps/studio/components/interfaces/Integrations/Vault/Secrets/DeleteSecretModal.tsx+++ b/apps/studio/components/interfaces/Integrations/Vault/Secrets/DeleteSecretModal.tsx@@ -68,7 +68,7 @@ export const DeleteSecretModal = () => {<div className="space-y-1"><p className="text-sm">{selectedSecret?.description}</p><p className="text-sm text-foreground-light">- ID: <span className="font-mono">{selectedSecret?.id}</span>+ ID: <code className="text-code-inline">{selectedSecret?.id}</code></p></div></Modal.Content>diff --git a/apps/studio/components/interfaces/Integrations/Vault/Secrets/EditSecretModal.tsx b/apps/studio/components/interfaces/Integrations/Vault/Secrets/EditSecretModal.tsxindex 89247a01ec5..d17af31783b 100644--- a/apps/studio/components/interfaces/Integrations/Vault/Secrets/EditSecretModal.tsx+++ b/apps/studio/components/interfaces/Integrations/Vault/Secrets/EditSecretModal.tsx@@ -186,7 +186,7 @@ export const EditSecretModal = () => {aria-label={showSecretValue ? `Hide secret value` : `Show secret value`}- className="absolute right-2 top-1 px-3 py-2"+ className="absolute right-1 top-1 w-7"icon={showSecretValue ? <EyeOff /> : <Eye />}onClick={() => setShowSecretValue(!showSecretValue)}/>diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsxindex d6b500ce8c6..86a86b4d6d3 100644--- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx+++ b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx@@ -1,3 +1,4 @@+import { wrapWithRollback } from '@supabase/pg-meta/src/query'import { useParams } from 'common'import type { QueryPlanRow } from 'components/interfaces/ExplainVisualizer/ExplainVisualizer.types'import { FilterPill } from 'components/interfaces/QueryPerformance/components/FilterPill'@@ -5,7 +6,6 @@ import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/Layimport { FilterPopover } from 'components/ui/FilterPopover'import TwoOptionToggle from 'components/ui/TwoOptionToggle'import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'-import { wrapWithRollback } from 'data/sql/utils/transaction'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { Search, TextSearch, X } from 'lucide-react'import { useRouter } from 'next/router'@@ -22,6 +22,7 @@ import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import { buildQueryInsightFixPrompt } from '../../QueryPerformance/QueryPerformance.ai'import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'import { useQueryInsightsIssues } from '../hooks/useQueryInsightsIssues'+import { useQueryInsightsTableColumns } from '../hooks/useQueryInsightsTableColumns'import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'import { QueryInsightsDetailSheet } from './QueryInsightsDetailSheet'import type { IssueFilter, Mode } from './QueryInsightsTable.types'@@ -31,7 +32,6 @@ import {getQueryType,getTableName,} from './QueryInsightsTable.utils'-import { useQueryInsightsTableColumns } from '../hooks/useQueryInsightsTableColumns'interface QueryInsightsTableProps {data: QueryPerformanceRow[]diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex 56c376be175..651365de99d 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -1,4 +1,5 @@import type { Monaco } from '@monaco-editor/react'+import { wrapWithRollback } from '@supabase/pg-meta/src/query'import { useQueryClient } from '@tanstack/react-query'import { IS_PLATFORM, LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'import {@@ -14,7 +15,6 @@ import { constructHeaders, isValidConnString } from 'data/fetchers'import { lintKeys } from 'data/lint/keys'import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'-import { wrapWithRollback } from 'data/sql/utils/transaction'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { isError } from 'data/utils/error-check'import { useOrgAiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'diff --git a/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.utils.ts b/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.utils.tsindex 0e97ada28a6..6cb06f08be7 100644--- a/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.utils.ts+++ b/apps/studio/components/interfaces/Settings/API/DataApiEnableSwitch.utils.ts@@ -1,7 +1,7 @@-import { unsafeEntitiesInApiSql } from '@/data/queries/sql/tables-without-rls'-import { executeSql } from '@/data/sql/execute-sql-query'+import { getUnsafeEntitiesInApiSql } from '@supabase/pg-meta'import type { EnableCheckAction, EnableCheckState } from './DataApiEnableSwitch.types'+import { executeSql } from '@/data/sql/execute-sql-query'export type ExposedEntity = {schema: string@@ -31,7 +31,7 @@ export async function queryUnsafeEntitiesInApi({const { result } = await executeSql<Array<ExposedEntity>>({projectRef,connectionString,- sql: unsafeEntitiesInApiSql(schemas),+ sql: getUnsafeEntitiesInApiSql({ schemas }),queryKey: ['unsafe-entities-in-api'],})diff --git a/apps/studio/data/enumerated-types/enumerated-type-create-mutation.ts b/apps/studio/data/enumerated-types/enumerated-type-create-mutation.tsindex 9de89157cb1..afd096d583b 100644--- a/apps/studio/data/enumerated-types/enumerated-type-create-mutation.ts+++ b/apps/studio/data/enumerated-types/enumerated-type-create-mutation.ts@@ -1,9 +1,10 @@+import { getCreateEnumeratedTypeSQL } from '@supabase/pg-meta'+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'+import { enumeratedTypesKeys } from './keys'export type EnumeratedTypeCreateVariables = {@@ -23,12 +24,7 @@ export async function createEnumeratedType({description,values,}: EnumeratedTypeCreateVariables) {- const createSql = `create type "${schema}"."${name}" as enum (${values- .map((x) => `'${x}'`)- .join(', ')});`- const commentSql =- description !== undefined ? `comment on type "${schema}"."${name}" is '${description}';` : ''- const sql = wrapWithTransaction(`${createSql} ${commentSql}`)+ const sql = getCreateEnumeratedTypeSQL({ schema, name, values, description })const { result } = await executeSql({ projectRef, connectionString, sql })return result}diff --git a/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.ts b/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.tsindex 0a867bcec9b..2a9fabe5276 100644--- a/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.ts+++ b/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.ts@@ -1,8 +1,9 @@+import { getDeleteEnumeratedTypeSQL } from '@supabase/pg-meta'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import { executeSql } from 'data/sql/execute-sql-query'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'+import { enumeratedTypesKeys } from './keys'export type EnumeratedTypeDeleteVariables = {@@ -18,7 +19,7 @@ export async function deleteEnumeratedType({name,schema,}: EnumeratedTypeDeleteVariables) {- const sql = `drop type if exists ${schema}."${name}"`+ const sql = getDeleteEnumeratedTypeSQL({ schema, name })const { result } = await executeSql({ projectRef, connectionString, sql })return result}diff --git a/apps/studio/data/enumerated-types/enumerated-type-update-mutation.ts b/apps/studio/data/enumerated-types/enumerated-type-update-mutation.tsindex aa220bc5360..6ec142828db 100644--- a/apps/studio/data/enumerated-types/enumerated-type-update-mutation.ts+++ b/apps/studio/data/enumerated-types/enumerated-type-update-mutation.ts@@ -1,9 +1,10 @@+import { getUpdateEnumeratedTypeSQL } from '@supabase/pg-meta'+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'+import { enumeratedTypesKeys } from './keys'export type EnumeratedTypeUpdateVariables = {@@ -23,38 +24,7 @@ export async function updateEnumeratedType({description,values = [],}: EnumeratedTypeUpdateVariables) {- const statements: string[] = []- if (name.original !== name.updated) {- statements.push(`alter type "${schema}"."${name.original}" rename to "${name.updated}";`)- }- if (values.length > 0) {- values.forEach((x, idx) => {- if (x.isNew) {- if (idx === 0) {- // Consider if any new enums were added before any existing enums- const firstExistingEnumValue = values.find((x) => !x.isNew)- statements.push(- `alter type "${schema}"."${name.updated}" add value '${x.updated}' before '${firstExistingEnumValue?.original}';`- )- } else {- statements.push(- `alter type "${schema}"."${name.updated}" add value '${x.updated}' after '${- values[idx - 1].updated- }';`- )- }- } else if (x.original !== x.updated) {- statements.push(- `alter type "${schema}"."${name.updated}" rename value '${x.original}' to '${x.updated}';`- )- }- })- }- if (description !== undefined) {- statements.push(`comment on type "${schema}"."${name.updated}" is '${description}';`)- }-- const sql = wrapWithTransaction(statements.join(' '))+ const sql = getUpdateEnumeratedTypeSQL({ schema, name, description, values })const { result } = await executeSql({ projectRef, connectionString, sql })return result}diff --git a/apps/studio/data/fdw/fdw-create-mutation.ts b/apps/studio/data/fdw/fdw-create-mutation.tsindex 9cd65975610..13b1dab55f0 100644--- a/apps/studio/data/fdw/fdw-create-mutation.ts+++ b/apps/studio/data/fdw/fdw-create-mutation.ts@@ -1,16 +1,14 @@+import { getCreateFDWSql } from '@supabase/pg-meta'+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'--import {- AvailableColumn,- WrapperMeta,-} from 'components/interfaces/Integrations/Wrappers/Wrappers.types'+import { WrapperMeta } from 'components/interfaces/Integrations/Wrappers/Wrappers.types'import { entityTypeKeys } from 'data/entity-types/keys'import { foreignTableKeys } from 'data/foreign-tables/keys'import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'import { vaultSecretsKeys } from 'data/vault/keys'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'+import { fdwKeys } from './keys'export type FDWCreateVariables = {@@ -28,208 +26,6 @@ export type FDWCreateVariables = {schemaOptions?: string[]}-export function getCreateFDWSql({- wrapperMeta,- formState,- mode,- tables,- sourceSchema,- targetSchema,- schemaOptions = [],-}: Omit<FDWCreateVariables, 'projectRef' | 'connectionString'>) {- const newSchemasSql = tables- .filter((table) => table.is_new_schema)- .map((table) => /* SQL */ `create schema if not exists ${table.schema_name};`)- .join('\n')-- const createWrapperSql = /* SQL */ `- create foreign data wrapper "${formState.wrapper_name}"- handler "${wrapperMeta.handlerName}"- validator "${wrapperMeta.validatorName}";- `-- const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)- const unencryptedOptions = wrapperMeta.server.options.filter((option) => !option.encrypted)-- const createEncryptedKeysSqlArray = encryptedOptions.map((option) => {- const key = `${formState.wrapper_name}_${option.name}`- // Escape single quotes in postgresql by doubling them up- const value = (formState[option.name] || '').replace(/'/g, "''")-- return /* SQL */ `- do $$- begin- -- Old wrappers has an implicit dependency on pgsodium. For new wrappers- -- we use Vault directly.- if (select extversion from pg_extension where extname = 'wrappers') in (- '0.1.0',- '0.1.1',- '0.1.4',- '0.1.5',- '0.1.6',- '0.1.7',- '0.1.8',- '0.1.9',- '0.1.10',- '0.1.11',- '0.1.12',- '0.1.14',- '0.1.15',- '0.1.16',- '0.1.17',- '0.1.18',- '0.1.19',- '0.2.0',- '0.3.0',- '0.3.1',- '0.4.0',- '0.4.1',- '0.4.2',- '0.4.3',- '0.4.4',- '0.4.5'- ) then- create extension if not exists pgsodium;-- perform pgsodium.create_key(- name := '${key}'- );-- perform vault.create_secret(- new_secret := '${value}',- new_name := '${key}',- new_key_id := (select id from pgsodium.valid_key where name = '${key}')- );- else- perform vault.create_secret(- new_secret := '${value}',- new_name := '${key}'- );- end if;- end $$;- `- })-- const createEncryptedKeysSql = createEncryptedKeysSqlArray.join('\n')-- const encryptedOptionsSqlArray = encryptedOptions- .filter((option) => formState[option.name])- .map((option) => `${option.name} ''%s''`)- const unencryptedOptionsSqlArray = unencryptedOptions- .filter((option) => formState[option.name])- // wrap all option names in double quotes to handle dots- // wrap all options values in single quotes, replace single quotes with 4 single quotes to escape them in SQL past the execute format- .map((option) => `"${option.name}" ''${formState[option.name].replace(/'/g, `''''`)}''`)- const optionsSqlArray = [...encryptedOptionsSqlArray, ...unencryptedOptionsSqlArray].join(',')-- const createServerSql = /* SQL */ `- do $$- declare- -- Old wrappers has an implicit dependency on pgsodium. For new wrappers- -- we use Vault directly.- is_using_old_wrappers bool;- ${encryptedOptions.map((option) => `v_${option.name} text;`).join('\n')}- begin- is_using_old_wrappers := (select extversion from pg_extension where extname = 'wrappers') in (- '0.1.0',- '0.1.1',- '0.1.4',- '0.1.5',- '0.1.6',- '0.1.7',- '0.1.8',- '0.1.9',- '0.1.10',- '0.1.11',- '0.1.12',- '0.1.14',- '0.1.15',- '0.1.16',- '0.1.17',- '0.1.18',- '0.1.19',- '0.2.0',- '0.3.0',- '0.3.1',- '0.4.0',- '0.4.1',- '0.4.2',- '0.4.3',- '0.4.4',- '0.4.5'- );- ${encryptedOptions- .map(- (option) => /* SQL */ `- if is_using_old_wrappers then- select id into v_${option.name} from pgsodium.valid_key where name = '${formState.wrapper_name}_${option.name}' limit 1;- else- select id into v_${option.name} from vault.secrets where name = '${formState.wrapper_name}_${option.name}' limit 1;- end if;- `- )- .join('\n')}-- execute format(- E'create server "${formState.server_name}" foreign data wrapper "${formState.wrapper_name}" options (${optionsSqlArray});',- ${encryptedOptions- .filter((option) => formState[option.name])- .map((option) => `v_${option.name}`)- .join(',\n')}- );- end $$;- `-- const createTablesSql = tables- .map((newTable) => {- const columns: AvailableColumn[] = newTable.columns-- return /* SQL */ `- create foreign table "${newTable.schema_name}"."${newTable.table_name}" (- ${columns.map((column) => `"${column.name}" ${column.type}`).join(',\n ')}- )- server ${formState.server_name}- options (- ${Object.entries(newTable)- .filter(- ([key, value]) =>- key !== 'table_name' &&- key !== 'schema_name' &&- key !== 'columns' &&- key !== 'index' &&- key !== 'is_new_schema' &&- Boolean(value)- )- .map(([key, value]) => `${key} '${value}'`)- .join(',\n ')}- );- `- })- .join('\n\n')-- const options = [...schemaOptions, "strict 'true'"].join(', ')-- const importForeignSchemaSql = /* SQL */ `- import foreign schema "${sourceSchema}" from server ${formState.server_name} into ${targetSchema} options (${options});-`-- const sql = /* SQL */ `- ${newSchemasSql}-- ${createWrapperSql}-- ${createEncryptedKeysSql}-- ${createServerSql}-- ${mode === 'tables' ? createTablesSql : ''}-- ${mode === 'schema' ? importForeignSchemaSql : ''}- `-- return sql-}-export async function createFDW({ projectRef, connectionString, ...rest }: FDWCreateVariables) {const sql = wrapWithTransaction(getCreateFDWSql(rest))const { result } = await executeSql({ projectRef, connectionString, sql })diff --git a/apps/studio/data/fdw/fdw-delete-mutation.ts b/apps/studio/data/fdw/fdw-delete-mutation.tsindex 179be61e648..b2088ffd012 100644--- a/apps/studio/data/fdw/fdw-delete-mutation.ts+++ b/apps/studio/data/fdw/fdw-delete-mutation.ts@@ -1,13 +1,14 @@+import { getDeleteFDWSql } from '@supabase/pg-meta'+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import type { WrapperMeta } from 'components/interfaces/Integrations/Wrappers/Wrappers.types'import { entityTypeKeys } from 'data/entity-types/keys'import { foreignTableKeys } from 'data/foreign-tables/keys'import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'import { vaultSecretsKeys } from 'data/vault/keys'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'+import { fdwKeys } from './keys'export type FDWDeleteVariables = {@@ -17,69 +18,6 @@ export type FDWDeleteVariables = {wrapperMeta: WrapperMeta}-export const getDeleteFDWSql = ({- wrapper,- wrapperMeta,-}: Pick<FDWDeleteVariables, 'wrapper' | 'wrapperMeta'>) => {- const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)-- const deleteEncryptedSecretsSqlArray = encryptedOptions.map((option) => {- const key = `${wrapper.name}_${option.name}`-- return /* SQL */ `- do $$- begin- -- Old wrappers has an implicit dependency on pgsodium. For new wrappers- -- we use Vault directly.- if (select extversion from pg_extension where extname = 'wrappers') in (- '0.1.0',- '0.1.1',- '0.1.4',- '0.1.5',- '0.1.6',- '0.1.7',- '0.1.8',- '0.1.9',- '0.1.10',- '0.1.11',- '0.1.12',- '0.1.14',- '0.1.15',- '0.1.16',- '0.1.17',- '0.1.18',- '0.1.19',- '0.2.0',- '0.3.0',- '0.3.1',- '0.4.0',- '0.4.1',- '0.4.2',- '0.4.3',- '0.4.4',- '0.4.5'- ) then- delete from vault.secrets where key_id = (select id from pgsodium.valid_key where name = '${key}');-- delete from pgsodium.key where name = '${key}';- else- delete from vault.secrets where name = '${key}';- end if;- end $$;- `- })-- const deleteEncryptedSecretsSql = deleteEncryptedSecretsSqlArray.join('\n')-- const sql = /* SQL */ `- drop foreign data wrapper if exists "${wrapper.name}" cascade;-- ${deleteEncryptedSecretsSql}- `-- return sql-}-export async function deleteFDW({projectRef,connectionString,diff --git a/apps/studio/data/fdw/fdw-drop-foreign-table-mutation.ts b/apps/studio/data/fdw/fdw-drop-foreign-table-mutation.tsindex fb8d243fec5..81f7e90cb8a 100644--- a/apps/studio/data/fdw/fdw-drop-foreign-table-mutation.ts+++ b/apps/studio/data/fdw/fdw-drop-foreign-table-mutation.ts@@ -1,11 +1,12 @@+import { getDropForeignTableSql } from '@supabase/pg-meta'+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import { entityTypeKeys } from 'data/entity-types/keys'import { foreignTableKeys } from 'data/foreign-tables/keys'import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'+import { fdwKeys } from './keys'export type FDWDropForeignTableVariables = {@@ -15,23 +16,14 @@ export type FDWDropForeignTableVariables = {tableName: string}-export function getDropForeignTableSql({- schemaName,- tableName,-}: Omit<FDWDropForeignTableVariables, 'projectRef' | 'connectionString'>) {- const sql = /* SQL */ `-drop foreign table if exists "${schemaName}"."${tableName}";-`-- return sql-}-export async function dropForeignTable({projectRef,connectionString,...rest}: FDWDropForeignTableVariables) {- const sql = wrapWithTransaction(getDropForeignTableSql(rest))+ const sql = wrapWithTransaction(+ getDropForeignTableSql({ schema: rest.schemaName, table: rest.tableName })+ )const { result } = await executeSql({ projectRef, connectionString, sql })return result}diff --git a/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts b/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.tsindex fd3f3262fe9..c59421f3e36 100644--- a/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts+++ b/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts@@ -1,8 +1,9 @@+import { getImportForeignSchemaSql } from '@supabase/pg-meta'+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'import { entityTypeKeys } from 'data/entity-types/keys'import { foreignTableKeys } from 'data/foreign-tables/keys'import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'import { vaultSecretsKeys } from 'data/vault/keys'import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'@@ -18,21 +19,6 @@ export type FDWImportForeignSchemaVariables = {schemaOptions?: string[]}-export function getImportForeignSchemaSql({- serverName,- sourceSchema,- targetSchema,- schemaOptions = [],-}: Omit<FDWImportForeignSchemaVariables, 'projectRef' | 'connectionString'>) {- const options = [...schemaOptions, "strict 'true'"].join(', ')-- const sql = /* SQL */ `- import foreign schema "${sourceSchema}" from server ${serverName} into ${targetSchema} options (${options});-`-- return sql-}-export async function importForeignSchema({projectRef,connectionString,diff --git a/apps/studio/data/fdw/fdw-update-mutation.ts b/apps/studio/data/fdw/fdw-update-mutation.tsindex 7ef5cefb309..c7c8db15701 100644--- a/apps/studio/data/fdw/fdw-update-mutation.ts+++ b/apps/studio/data/fdw/fdw-update-mutation.ts@@ -1,15 +1,14 @@+import { getCreateFDWSql, getDeleteFDWSql, getUpdateFDWSql } from '@supabase/pg-meta'+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import type { WrapperMeta } from 'components/interfaces/Integrations/Wrappers/Wrappers.types'import { entityTypeKeys } from 'data/entity-types/keys'import { foreignTableKeys } from 'data/foreign-tables/keys'import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'import { vaultSecretsKeys } from 'data/vault/keys'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions } from 'types'-import { getCreateFDWSql } from './fdw-create-mutation'-import { getDeleteFDWSql } from './fdw-delete-mutation'+import { FDW } from './fdws-query'import { fdwKeys } from './keys'@@ -25,31 +24,6 @@ export type FDWUpdateVariables = {skipInvalidation?: boolean}-export const getUpdateFDWSql = ({- wrapper,- wrapperMeta,- formState,- tables,-}: Pick<FDWUpdateVariables, 'wrapper' | 'wrapperMeta' | 'formState' | 'tables'>) => {- const deleteWrapperSql = getDeleteFDWSql({ wrapper, wrapperMeta })- const createWrapperSql = getCreateFDWSql({- wrapperMeta,- formState,- tables,- mode: 'tables',- sourceSchema: '',- targetSchema: '',- })-- const sql = /* SQL */ `- ${deleteWrapperSql}-- ${createWrapperSql}- `-- return sql-}-export async function updateFDW({projectRef,connectionString,diff --git a/apps/studio/data/fdw/fdws-query.ts b/apps/studio/data/fdw/fdws-query.tsindex 19a41f1675b..ab8d1700f39 100644--- a/apps/studio/data/fdw/fdws-query.ts+++ b/apps/studio/data/fdw/fdws-query.ts@@ -1,47 +1,10 @@+import { getFDWsSql } from '@supabase/pg-meta'import { useQuery } from '@tanstack/react-query'import { UseCustomQueryOptions } from 'types'+import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'import { fdwKeys } from './keys'-export const getFDWsSql = () => {- const sql = /* SQL */ `- select- s.oid as "id",- w.fdwname as "name",- s.srvname as "server_name",- s.srvoptions as "server_options",- c.proname as "handler",- (- select jsonb_agg(- jsonb_build_object(- 'id', c.oid::bigint,- 'schema', relnamespace::regnamespace::text,- 'name', c.relname,- 'columns', (- select jsonb_agg(- jsonb_build_object(- 'name', a.attname,- 'type', pg_catalog.format_type(a.atttypid, a.atttypmod)- )- )- from pg_catalog.pg_attribute a- where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped- ),- 'options', t.ftoptions- )- )- from pg_catalog.pg_class c- join pg_catalog.pg_foreign_table t on c.oid = t.ftrelid- where c.oid = any (select t.ftrelid from pg_catalog.pg_foreign_table t where t.ftserver = s.oid)- ) as "tables"- from pg_catalog.pg_foreign_server s- join pg_catalog.pg_foreign_data_wrapper w on s.srvfdw = w.oid- join pg_catalog.pg_proc c on w.fdwhandler = c.oid;- `-- return sql-}-export type FDWColumn = {name: stringtype: stringdiff --git a/apps/studio/data/sql/execute-sql-query.ts b/apps/studio/data/sql/execute-sql-query.tsindex 79626f6c0ed..fbb8221f398 100644--- a/apps/studio/data/sql/execute-sql-query.ts+++ b/apps/studio/data/sql/execute-sql-query.ts@@ -1,12 +1,9 @@+import { ROLE_IMPERSONATION_NO_RESULTS, ROLE_IMPERSONATION_SQL_LINE_COUNT } from '@supabase/pg-meta'import { DEFAULT_PLATFORM_APPLICATION_NAME } from '@supabase/pg-meta/src/constants'import { QueryKey, useQuery } from '@tanstack/react-query'import { handleError as handleErrorFetchers, post } from 'data/fetchers'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { MB, PROJECT_STATUS } from 'lib/constants'-import {- ROLE_IMPERSONATION_NO_RESULTS,- ROLE_IMPERSONATION_SQL_LINE_COUNT,-} from 'lib/role-impersonation'import type { ResponseError, UseCustomQueryOptions } from 'types'import { sqlKeys } from './keys'diff --git a/apps/studio/data/sql/utils/transaction.ts b/apps/studio/data/sql/utils/transaction.tsdeleted file mode 100644index e1e716da170..00000000000--- a/apps/studio/data/sql/utils/transaction.ts+++ /dev/null@@ -1,19 +0,0 @@-export function wrapWithTransaction(sql: string) {- return /* SQL */ `- begin;-- ${sql}-- commit;- `-}--export function wrapWithRollback(sql: string) {- return /* SQL */ `- begin;-- ${sql}-- rollback;- `-}diff --git a/apps/studio/data/storage/bucket-prefix-delete-mutation.ts b/apps/studio/data/storage/bucket-prefix-delete-mutation.tsindex d2b7d37f1ae..e659ab82add 100644--- a/apps/studio/data/storage/bucket-prefix-delete-mutation.ts+++ b/apps/studio/data/storage/bucket-prefix-delete-mutation.ts@@ -1,3 +1,4 @@+import { getDeleteBucketPrefixSQL } from '@supabase/pg-meta'import { executeSql } from 'data/sql/execute-sql-query'/**@@ -23,9 +24,7 @@ export const deleteBucketPrefix = async (if (!bucketId) throw new Error('bucketId is required')if (!prefix) throw new Error('prefix is required')- const sql = /* SQL */ `-select storage.delete_prefix('${bucketId}', '${prefix}');-`.trim()+ const sql = getDeleteBucketPrefixSQL({ bucketId, prefix })const { result } = await executeSql({ projectRef, connectionString, sql, queryKey: ['delete-bucket-prefix'] },diff --git a/apps/studio/data/table-editor/table-editor-query-sql.ts b/apps/studio/data/table-editor/table-editor-query-sql.tsdeleted file mode 100644index 26fdacba943..00000000000--- a/apps/studio/data/table-editor/table-editor-query-sql.ts+++ /dev/null@@ -1,311 +0,0 @@-import minify from 'pg-minify'--export function getTableEditorSql(id?: number) {- if (!id) return ''-- return minify(/* SQL */ `- with base_table_info as (- select- c.oid::int8 as id,- nc.nspname as schema,- c.relname as name,- c.relkind,- c.relrowsecurity as rls_enabled,- c.relforcerowsecurity as rls_forced,- c.relreplident,- c.relowner,- obj_description(c.oid) as comment,- fs.srvname as foreign_server_name,- fdw.fdwname as foreign_data_wrapper_name,- fdw_handler.proname as foreign_data_wrapper_handler- from pg_class c- join pg_namespace nc on nc.oid = c.relnamespace- left join pg_foreign_table ft on ft.ftrelid = c.oid- left join pg_foreign_server fs on fs.oid = ft.ftserver- left join pg_foreign_data_wrapper fdw on fdw.oid = fs.srvfdw- left join pg_proc fdw_handler on fdw.fdwhandler = fdw_handler.oid- where c.oid = ${id}- and not pg_is_other_temp_schema(nc.oid)- and (- pg_has_role(c.relowner, 'USAGE')- or has_table_privilege(- c.oid,- 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'- )- or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')- )- ),- table_stats as (- select- b.id,- case- when b.relreplident = 'd' then 'DEFAULT'- when b.relreplident = 'i' then 'INDEX'- when b.relreplident = 'f' then 'FULL'- else 'NOTHING'- end as replica_identity,- pg_total_relation_size(format('%I.%I', b.schema, b.name))::int8 as bytes,- pg_size_pretty(pg_total_relation_size(format('%I.%I', b.schema, b.name))) as size,- pg_stat_get_live_tuples(b.id) as live_rows_estimate,- pg_stat_get_dead_tuples(b.id) as dead_rows_estimate- from base_table_info b- where b.relkind in ('r', 'p')- ),- primary_keys as (- select- i.indrelid as table_id,- jsonb_agg(- jsonb_build_object(- 'schema', n.nspname,- 'table_name', c.relname,- 'table_id', i.indrelid::int8,- 'name', a.attname- )- order by array_position(i.indkey, a.attnum)- ) as primary_keys- from pg_index i- join pg_class c on i.indrelid = c.oid- join pg_namespace n on c.relnamespace = n.oid- join pg_attribute a on a.attrelid = c.oid and a.attnum = any(i.indkey)- where i.indisprimary- group by i.indrelid- ),- index_cols as (- select- i.indrelid as table_id,- i.indkey,- array_agg(- a.attname- order by array_position(i.indkey, a.attnum)- ) as columns- from pg_index i- join pg_class c on i.indrelid = c.oid- join pg_attribute a on a.attrelid = c.oid- and a.attnum = any(i.indkey)- where i.indisunique- and i.indisprimary = false- group by i.indrelid, i.indkey- ),- unique_indexes as (- select- ic.table_id,- jsonb_agg(- jsonb_build_object(- 'schema', n.nspname,- 'table_name', c.relname,- 'table_id', ic.table_id::int8,- 'columns', ic.columns- )- ) as unique_indexes- from index_cols ic- join pg_class c on c.oid = ic.table_id- join pg_namespace n on n.oid = c.relnamespace- group by ic.table_id- ),- relationships as (- select- c.conrelid as source_id,- c.confrelid as target_id,- jsonb_build_object(- 'id', c.oid::int8,- 'constraint_name', c.conname,- 'deletion_action', c.confdeltype,- 'update_action', c.confupdtype,- 'source_schema', nsa.nspname,- 'source_table_name', csa.relname,- 'source_column_name', sa.attname,- 'target_table_schema', nta.nspname,- 'target_table_name', cta.relname,- 'target_column_name', ta.attname- ) as rel_info- from pg_constraint c- join pg_class csa on c.conrelid = csa.oid- join pg_namespace nsa on csa.relnamespace = nsa.oid- join pg_attribute sa on (sa.attrelid = c.conrelid and sa.attnum = any(c.conkey))- join pg_class cta on c.confrelid = cta.oid- join pg_namespace nta on cta.relnamespace = nta.oid- join pg_attribute ta on (ta.attrelid = c.confrelid and ta.attnum = any(c.confkey))- where c.contype = 'f'- ),- columns as (- select- a.attrelid as table_id,- jsonb_agg(jsonb_build_object(- 'id', (a.attrelid || '.' || a.attnum),- 'table_id', c.oid::int8,- 'schema', nc.nspname,- 'table', c.relname,- 'ordinal_position', a.attnum,- 'name', a.attname,- 'default_value', case- when a.atthasdef then pg_get_expr(ad.adbin, ad.adrelid)- else null- end,- 'data_type', case- when t.typtype = 'd' then- case- when bt.typelem <> 0::oid and bt.typlen = -1 then 'ARRAY'- when nbt.nspname = 'pg_catalog' then format_type(t.typbasetype, null)- else 'USER-DEFINED'- end- else- case- when t.typelem <> 0::oid and t.typlen = -1 then 'ARRAY'- when nt.nspname = 'pg_catalog' then format_type(a.atttypid, null)- else 'USER-DEFINED'- end- end,- 'format', case- when t.typtype = 'e' then- case- when nt.nspname <> 'public' then concat(nt.nspname, '.', coalesce(bt.typname, t.typname))- else coalesce(bt.typname, t.typname)- end- else- coalesce(bt.typname, t.typname)- end,- 'is_identity', a.attidentity in ('a', 'd'),- 'identity_generation', case a.attidentity- when 'a' then 'ALWAYS'- when 'd' then 'BY DEFAULT'- else null- end,- 'is_generated', a.attgenerated in ('s'),- 'is_nullable', not (a.attnotnull or t.typtype = 'd' and t.typnotnull),- 'is_updatable', (- b.relkind in ('r', 'p') or- (b.relkind in ('v', 'f') and pg_column_is_updatable(b.id, a.attnum, false))- ),- 'is_unique', uniques.table_id is not null,- 'check', check_constraints.definition,- 'comment', col_description(c.oid, a.attnum),- 'enums', coalesce(- (- select jsonb_agg(e.enumlabel order by e.enumsortorder)- from pg_catalog.pg_enum e- where e.enumtypid = coalesce(bt.oid, t.oid)- or e.enumtypid = coalesce(bt.typelem, t.typelem)- ),- '[]'::jsonb- )- ) order by a.attnum) as columns- from pg_attribute a- join base_table_info b on a.attrelid = b.id- join pg_class c on a.attrelid = c.oid- join pg_namespace nc on c.relnamespace = nc.oid- left join pg_attrdef ad on (a.attrelid = ad.adrelid and a.attnum = ad.adnum)- join pg_type t on a.atttypid = t.oid- join pg_namespace nt on t.typnamespace = nt.oid- left join pg_type bt on (t.typtype = 'd' and t.typbasetype = bt.oid)- left join pg_namespace nbt on bt.typnamespace = nbt.oid- left join (- select- conrelid as table_id,- conkey[1] as ordinal_position- from pg_catalog.pg_constraint- where contype = 'u' and cardinality(conkey) = 1- group by conrelid, conkey[1]- ) as uniques on uniques.table_id = a.attrelid and uniques.ordinal_position = a.attnum- left join (- select distinct on (conrelid, conkey[1])- conrelid as table_id,- conkey[1] as ordinal_position,- substring(- pg_get_constraintdef(oid, true),- 8,- length(pg_get_constraintdef(oid, true)) - 8- ) as definition- from pg_constraint- where contype = 'c' and cardinality(conkey) = 1- order by conrelid, conkey[1], oid asc- ) as check_constraints on check_constraints.table_id = a.attrelid- and check_constraints.ordinal_position = a.attnum- where a.attnum > 0- and not a.attisdropped- group by a.attrelid- )- select- case b.relkind- when 'r' then jsonb_build_object(- 'entity_type', b.relkind,- 'id', b.id,- 'schema', b.schema,- 'name', b.name,- 'rls_enabled', b.rls_enabled,- 'rls_forced', b.rls_forced,- 'replica_identity', ts.replica_identity,- 'bytes', ts.bytes,- 'size', ts.size,- 'live_rows_estimate', ts.live_rows_estimate,- 'dead_rows_estimate', ts.dead_rows_estimate,- 'comment', b.comment,- 'primary_keys', coalesce(pk.primary_keys, '[]'::jsonb),- 'unique_indexes', coalesce(ui.unique_indexes, '[]'::jsonb),- 'relationships', coalesce(- (select jsonb_agg(r.rel_info)- from relationships r- where r.source_id = b.id or r.target_id = b.id),- '[]'::jsonb- ),- 'columns', coalesce(c.columns, '[]'::jsonb)- )- when 'p' then jsonb_build_object(- 'entity_type', b.relkind,- 'id', b.id,- 'schema', b.schema,- 'name', b.name,- 'rls_enabled', b.rls_enabled,- 'rls_forced', b.rls_forced,- 'replica_identity', ts.replica_identity,- 'bytes', ts.bytes,- 'size', ts.size,- 'live_rows_estimate', ts.live_rows_estimate,- 'dead_rows_estimate', ts.dead_rows_estimate,- 'comment', b.comment,- 'primary_keys', coalesce(pk.primary_keys, '[]'::jsonb),- 'unique_indexes', coalesce(ui.unique_indexes, '[]'::jsonb),- 'relationships', coalesce(- (select jsonb_agg(r.rel_info)- from relationships r- where r.source_id = b.id or r.target_id = b.id),- '[]'::jsonb- ),- 'columns', coalesce(c.columns, '[]'::jsonb)- )- when 'v' then jsonb_build_object(- 'entity_type', b.relkind,- 'id', b.id,- 'schema', b.schema,- 'name', b.name,- 'is_updatable', (pg_relation_is_updatable(b.id, false) & 20) = 20,- 'comment', b.comment,- 'columns', coalesce(c.columns, '[]'::jsonb)- )- when 'm' then jsonb_build_object(- 'entity_type', b.relkind,- 'id', b.id,- 'schema', b.schema,- 'name', b.name,- 'is_populated', true,- 'comment', b.comment,- 'columns', coalesce(c.columns, '[]'::jsonb)- )- when 'f' then jsonb_build_object(- 'entity_type', b.relkind,- 'id', b.id,- 'schema', b.schema,- 'name', b.name,- 'comment', b.comment,- 'foreign_server_name', b.foreign_server_name,- 'foreign_data_wrapper_name', b.foreign_data_wrapper_name,- 'foreign_data_wrapper_handler', b.foreign_data_wrapper_handler,- 'columns', coalesce(c.columns, '[]'::jsonb)- )- end as entity- from base_table_info b- left join table_stats ts on b.id = ts.id- left join primary_keys pk on b.id = pk.table_id- left join unique_indexes ui on b.id = ui.table_id- left join columns c on b.id = c.table_id;- `)-}diff --git a/apps/studio/data/table-editor/table-editor-query.ts b/apps/studio/data/table-editor/table-editor-query.tsindex a955e1010f0..d03fc2c6bf4 100644--- a/apps/studio/data/table-editor/table-editor-query.ts+++ b/apps/studio/data/table-editor/table-editor-query.ts@@ -1,10 +1,9 @@+import { getTableEditorSql } from '@supabase/pg-meta'import { QueryClient, queryOptions, useQuery } from '@tanstack/react-query'-import { id } from 'common-tags'import { UseCustomQueryOptions } from 'types'import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'import { tableEditorKeys } from './keys'-import { getTableEditorSql } from './table-editor-query-sql'import { Entity } from './table-editor-types'type TableEditorArgs = {@@ -24,7 +23,7 @@ export async function getTableEditor(throw new Error('id is required')}- const sql = getTableEditorSql(id)+ const sql = getTableEditorSql({ id })const { result } = await executeSql({projectRef,diff --git a/apps/studio/data/table-rows/operation-queue-save-mutation.ts b/apps/studio/data/table-rows/operation-queue-save-mutation.tsindex d78eaf7569e..23fe3454517 100644--- a/apps/studio/data/table-rows/operation-queue-save-mutation.ts+++ b/apps/studio/data/table-rows/operation-queue-save-mutation.ts@@ -1,7 +1,7 @@+import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'import type { PendingAddRow } from 'components/grid/types'import { executeSql } from 'data/sql/execute-sql-query'-import { wrapWithTransaction } from 'data/sql/utils/transaction'import { RoleImpersonationState, wrapWithRoleImpersonation } from 'lib/role-impersonation'import { toast } from 'sonner'import { isRoleImpersonationEnabled } from 'state/role-impersonation-state'diff --git a/apps/studio/data/table-rows/table-rows-query.ts b/apps/studio/data/table-rows/table-rows-query.tsindex 34bb5a9788f..efc3cb72769 100644--- a/apps/studio/data/table-rows/table-rows-query.ts+++ b/apps/studio/data/table-rows/table-rows-query.ts@@ -1,3 +1,4 @@+import { ROLE_IMPERSONATION_NO_RESULTS } from '@supabase/pg-meta'import { Query, type QueryFilter } from '@supabase/pg-meta/src/query'import { getTableRowsSql } from '@supabase/pg-meta/src/query/table-row-query'import { useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'@@ -7,11 +8,7 @@ import { Filter, Sort, SupaRow, SupaTable } from 'components/grid/types'import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'import { prefetchTableEditor } from 'data/table-editor/table-editor-query'import { isMsSqlForeignTable } from 'data/table-editor/table-editor-types'-import {- ROLE_IMPERSONATION_NO_RESULTS,- RoleImpersonationState,- wrapWithRoleImpersonation,-} from 'lib/role-impersonation'+import { RoleImpersonationState, wrapWithRoleImpersonation } from 'lib/role-impersonation'import { isRoleImpersonationEnabled } from 'state/role-impersonation-state'import { ResponseError, UseCustomQueryOptions } from 'types'diff --git a/apps/studio/data/vault/vault-secret-create-mutation.ts b/apps/studio/data/vault/vault-secret-create-mutation.tsindex e70c8462ceb..3d3334bf0fb 100644--- a/apps/studio/data/vault/vault-secret-create-mutation.ts+++ b/apps/studio/data/vault/vault-secret-create-mutation.ts@@ -1,9 +1,9 @@+import { getCreateVaultSecretSQL } from '@supabase/pg-meta'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import { executeSql } from 'data/sql/execute-sql-query'-import { quoteLiteral } from 'lib/pg-format'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions, VaultSecret } from 'types'+import { vaultSecretsKeys } from './keys'export type VaultSecretCreateVariables = {@@ -17,13 +17,9 @@ export async function createVaultSecret({...newSecret}: VaultSecretCreateVariables) {const { name, description, secret } = newSecret- const sql = /* SQL */ `-select vault.create_secret(- new_secret := ${quoteLiteral(secret)}- ${name ? `, new_name := ${quoteLiteral(name)}` : ''}- ${description ? `, new_description := ${quoteLiteral(description)}` : ''}-)-`++ if (!secret) throw new Error('Secret value is required')+ const sql = getCreateVaultSecretSQL({ secret, name, description })const { result } = await executeSql({ projectRef, connectionString, sql })return resultdiff --git a/apps/studio/data/vault/vault-secret-update-mutation.ts b/apps/studio/data/vault/vault-secret-update-mutation.tsindex 1619543e67a..e9c466b9f0c 100644--- a/apps/studio/data/vault/vault-secret-update-mutation.ts+++ b/apps/studio/data/vault/vault-secret-update-mutation.ts@@ -1,9 +1,9 @@+import { getUpdateVaultSecretSQL } from '@supabase/pg-meta'import { useMutation, useQueryClient } from '@tanstack/react-query'-import { toast } from 'sonner'-import { executeSql } from 'data/sql/execute-sql-query'-import { quoteLiteral } from 'lib/pg-format'+import { toast } from 'sonner'import type { ResponseError, UseCustomMutationOptions, VaultSecret } from 'types'+import { vaultSecretsKeys } from './keys'export type VaultSecretUpdateVariables = {@@ -19,14 +19,7 @@ export async function updateVaultSecret({...payload}: VaultSecretUpdateVariables) {const { name, description, secret } = payload- const sql = /* SQL */ `-select vault.update_secret(- secret_id := ${quoteLiteral(id)}- ${secret ? `, new_secret := ${quoteLiteral(secret)}` : ''}- ${name ? `, new_name := ${quoteLiteral(name)}` : ''}- ${description ? `, new_description := ${quoteLiteral(description)}` : ''}-)-`+ const sql = getUpdateVaultSecretSQL({ id, secret, name, description })const { result } = await executeSql({ projectRef, connectionString, sql })return resultdiff --git a/apps/studio/lib/api/self-hosted/lints.ts b/apps/studio/lib/api/self-hosted/lints.tsindex b650c3d3f35..ccf3e5ba1a2 100644--- a/apps/studio/lib/api/self-hosted/lints.ts+++ b/apps/studio/lib/api/self-hosted/lints.ts@@ -1,5 +1,7 @@+import { enrichLintsQuery, getLintsSQL } from '@supabase/pg-meta'import { paths } from 'api-types'import { DOCS_URL } from 'lib/constants'+import { executeQuery } from './query'interface GetLintsOptions {@@ -8,1422 +10,12 @@ interface GetLintsOptions {}export async function getLints({ headers, exposedSchemas }: GetLintsOptions) {+ const sql = getLintsSQL({ docsUrl: DOCS_URL })return await executeQuery<ResponseData[number]>({- query: enrichLintsQuery(LINT_SQL, exposedSchemas),+ query: enrichLintsQuery(sql, exposedSchemas),headers,})}export type ResponseData =paths['/platform/projects/{ref}/run-lints']['get']['responses']['200']['content']['application/json']--export const enrichLintsQuery = (query: string, exposedSchemas?: string) => {- return `-do $$-begin- set pg_stat_statements.track = none;-exception when others then- -- not a superuser or extension not installed, skip silently-end-$$;-${!!exposedSchemas ? `set local pgrst.db_schemas = '${exposedSchemas}';` : ''}--- source: dashboard--- user: ${'self host'}--- date: ${new Date().toISOString()}--${query}-`-}--/**- * Pulled from https://github.com/supabase/splinter/blob/main/splinter.sql- * Things to do after copy pasting from splinter.sql- * - Replace all "\`%s\`" with backquotes to escape the tick character ("\`%s\`")- * - Replace docs url with DOCS_URL (${DOCS_URL})- */-const LINT_SQL = /* SQL */ `set local search_path = '';--(-with foreign_keys as (- select- cl.relnamespace::regnamespace::text as schema_name,- cl.relname as table_name,- cl.oid as table_oid,- ct.conname as fkey_name,- ct.conkey as col_attnums- from- pg_catalog.pg_constraint ct- join pg_catalog.pg_class cl -- fkey owning table- on ct.conrelid = cl.oid- left join pg_catalog.pg_depend d- on d.objid = cl.oid- and d.deptype = 'e'- where- ct.contype = 'f' -- foreign key constraints- and d.objid is null -- exclude tables that are dependencies of extensions- and cl.relnamespace::regnamespace::text not in (- 'pg_catalog', 'information_schema', 'auth', 'storage', 'vault', 'extensions'- )-),-index_ as (- select- pi.indrelid as table_oid,- indexrelid::regclass as index_,- string_to_array(indkey::text, ' ')::smallint[] as col_attnums- from- pg_catalog.pg_index pi- where- indisvalid-)-select- 'unindexed_foreign_keys' as name,- 'Unindexed foreign keys' as title,- 'INFO' as level,- 'EXTERNAL' as facing,- array['PERFORMANCE'] as categories,- 'Identifies foreign key constraints without a covering index, which can impact database performance.' as description,- format(- 'Table \`%s.%s\` has a foreign key \`%s\` without a covering index. This can lead to suboptimal query performance.',- fk.schema_name,- fk.table_name,- fk.fkey_name- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0001_unindexed_foreign_keys' as remediation,- jsonb_build_object(- 'schema', fk.schema_name,- 'name', fk.table_name,- 'type', 'table',- 'fkey_name', fk.fkey_name,- 'fkey_columns', fk.col_attnums- ) as metadata,- format('unindexed_foreign_keys_%s_%s_%s', fk.schema_name, fk.table_name, fk.fkey_name) as cache_key-from- foreign_keys fk- left join index_ idx- on fk.table_oid = idx.table_oid- and fk.col_attnums = idx.col_attnums[1:array_length(fk.col_attnums, 1)]- left join pg_catalog.pg_depend dep- on idx.table_oid = dep.objid- and dep.deptype = 'e'-where- idx.index_ is null- and fk.schema_name not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and dep.objid is null -- exclude tables owned by extensions-order by- fk.schema_name,- fk.table_name,- fk.fkey_name)-union all-(-select- 'auth_users_exposed' as name,- 'Exposed Auth Users' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects if auth.users is exposed to anon or authenticated roles via a view or materialized view in schemas exposed to PostgREST, potentially compromising user data security.' as description,- format(- 'View/Materialized View "%s" in the public schema may expose \`auth.users\` data to anon or authenticated roles.',- c.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0002_auth_users_exposed' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'view',- 'exposed_to', array_remove(array_agg(DISTINCT case when pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') then 'anon' when pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') then 'authenticated' end), null)- ) as metadata,- format('auth_users_exposed_%s_%s', n.nspname, c.relname) as cache_key-from- -- Identify the oid for auth.users- pg_catalog.pg_class auth_users_pg_class- join pg_catalog.pg_namespace auth_users_pg_namespace- on auth_users_pg_class.relnamespace = auth_users_pg_namespace.oid- and auth_users_pg_class.relname = 'users'- and auth_users_pg_namespace.nspname = 'auth'- -- Depends on auth.users- join pg_catalog.pg_depend d- on d.refobjid = auth_users_pg_class.oid- join pg_catalog.pg_rewrite r- on r.oid = d.objid- join pg_catalog.pg_class c- on c.oid = r.ev_class- join pg_catalog.pg_namespace n- on n.oid = c.relnamespace- join pg_catalog.pg_class pg_class_auth_users- on d.refobjid = pg_class_auth_users.oid-where- d.deptype = 'n'- and (- pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')- or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')- )- and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))- -- Exclude self- and c.relname <> '0002_auth_users_exposed'- -- There are 3 insecure configurations- and- (- -- Materialized views don't support RLS so this is insecure by default- (c.relkind in ('m')) -- m for materialized view- or- -- Standard View, accessible to anon or authenticated that is security_definer- (- c.relkind = 'v' -- v for view- -- Exclude security invoker views- and not (- lower(coalesce(c.reloptions::text,'{}'))::text[]- && array[- 'security_invoker=1',- 'security_invoker=true',- 'security_invoker=yes',- 'security_invoker=on'- ]- )- )- or- -- Standard View, security invoker, but no RLS enabled on auth.users- (- c.relkind in ('v') -- v for view- -- is security invoker- and (- lower(coalesce(c.reloptions::text,'{}'))::text[]- && array[- 'security_invoker=1',- 'security_invoker=true',- 'security_invoker=yes',- 'security_invoker=on'- ]- )- and not pg_class_auth_users.relrowsecurity- )- )-group by- n.nspname,- c.relname,- c.oid)-union all-(-with policies as (- select- nsp.nspname as schema_name,- pb.tablename as table_name,- pc.relrowsecurity as is_rls_active,- polname as policy_name,- polpermissive as is_permissive, -- if not, then restrictive- (select array_agg(r::regrole) from unnest(polroles) as x(r)) as roles,- case polcmd- when 'r' then 'SELECT'- when 'a' then 'INSERT'- when 'w' then 'UPDATE'- when 'd' then 'DELETE'- when '*' then 'ALL'- end as command,- qual,- with_check- from- pg_catalog.pg_policy pa- join pg_catalog.pg_class pc- on pa.polrelid = pc.oid- join pg_catalog.pg_namespace nsp- on pc.relnamespace = nsp.oid- join pg_catalog.pg_policies pb- on pc.relname = pb.tablename- and nsp.nspname = pb.schemaname- and pa.polname = pb.policyname-)-select- 'auth_rls_initplan' as name,- 'Auth RLS Initialization Plan' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['PERFORMANCE'] as categories,- 'Detects if calls to \`current_setting()\` and \`auth.<function>()\` in RLS policies are being unnecessarily re-evaluated for each row' as description,- format(- 'Table \`%s.%s\` has a row level security policy \`%s\` that re-evaluates current_setting() or auth.<function>() for each row. This produces suboptimal query performance at scale. Resolve the issue by replacing \`auth.<function>()\` with \`(select auth.<function>())\`. See [docs](${DOCS_URL}/guides/database/postgres/row-level-security#call-functions-with-select) for more info.',- schema_name,- table_name,- policy_name- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0003_auth_rls_initplan' as remediation,- jsonb_build_object(- 'schema', schema_name,- 'name', table_name,- 'type', 'table'- ) as metadata,- format('auth_rls_init_plan_%s_%s_%s', schema_name, table_name, policy_name) as cache_key-from- policies-where- is_rls_active- -- NOTE: does not include realtime in support of monitoring policies on realtime.messages- and schema_name not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and (- -- Example: auth.uid()- (- qual like '%auth.uid()%'- and lower(qual) not like '%select auth.uid()%'- )- or (- qual like '%auth.jwt()%'- and lower(qual) not like '%select auth.jwt()%'- )- or (- qual like '%auth.role()%'- and lower(qual) not like '%select auth.role()%'- )- or (- qual like '%auth.email()%'- and lower(qual) not like '%select auth.email()%'- )- or (- qual like '%current\_setting(%)%'- and lower(qual) not like '%select current\_setting(%)%'- )- or (- with_check like '%auth.uid()%'- and lower(with_check) not like '%select auth.uid()%'- )- or (- with_check like '%auth.jwt()%'- and lower(with_check) not like '%select auth.jwt()%'- )- or (- with_check like '%auth.role()%'- and lower(with_check) not like '%select auth.role()%'- )- or (- with_check like '%auth.email()%'- and lower(with_check) not like '%select auth.email()%'- )- or (- with_check like '%current\_setting(%)%'- and lower(with_check) not like '%select current\_setting(%)%'- )- ))-union all-(-select- 'no_primary_key' as name,- 'No Primary Key' as title,- 'INFO' as level,- 'EXTERNAL' as facing,- array['PERFORMANCE'] as categories,- 'Detects if a table does not have a primary key. Tables without a primary key can be inefficient to interact with at scale.' as description,- format(- 'Table \`%s.%s\` does not have a primary key',- pgns.nspname,- pgc.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0004_no_primary_key' as remediation,- jsonb_build_object(- 'schema', pgns.nspname,- 'name', pgc.relname,- 'type', 'table'- ) as metadata,- format(- 'no_primary_key_%s_%s',- pgns.nspname,- pgc.relname- ) as cache_key-from- pg_catalog.pg_class pgc- join pg_catalog.pg_namespace pgns- on pgns.oid = pgc.relnamespace- left join pg_catalog.pg_index pgi- on pgi.indrelid = pgc.oid- left join pg_catalog.pg_depend dep- on pgc.oid = dep.objid- and dep.deptype = 'e'-where- pgc.relkind = 'r' -- regular tables- and pgns.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and dep.objid is null -- exclude tables owned by extensions-group by- pgc.oid,- pgns.nspname,- pgc.relname-having- max(coalesce(pgi.indisprimary, false)::int) = 0)-union all-(-select- 'unused_index' as name,- 'Unused Index' as title,- 'INFO' as level,- 'EXTERNAL' as facing,- array['PERFORMANCE'] as categories,- 'Detects if an index has never been used and may be a candidate for removal.' as description,- format(- 'Index \`%s\` on table \`%s.%s\` has not been used',- psui.indexrelname,- psui.schemaname,- psui.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0005_unused_index' as remediation,- jsonb_build_object(- 'schema', psui.schemaname,- 'name', psui.relname,- 'type', 'table'- ) as metadata,- format(- 'unused_index_%s_%s_%s',- psui.schemaname,- psui.relname,- psui.indexrelname- ) as cache_key--from- pg_catalog.pg_stat_user_indexes psui- join pg_catalog.pg_index pi- on psui.indexrelid = pi.indexrelid- left join pg_catalog.pg_depend dep- on psui.relid = dep.objid- and dep.deptype = 'e'-where- psui.idx_scan = 0- and not pi.indisunique- and not pi.indisprimary- and dep.objid is null -- exclude tables owned by extensions- and psui.schemaname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- ))-union all-(-select- 'multiple_permissive_policies' as name,- 'Multiple Permissive Policies' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['PERFORMANCE'] as categories,- 'Detects if multiple permissive row level security policies are present on a table for the same \`role\` and \`action\` (e.g. insert). Multiple permissive policies are suboptimal for performance as each policy must be executed for every relevant query.' as description,- format(- 'Table \`%s.%s\` has multiple permissive policies for role \`%s\` for action \`%s\`. Policies include \`%s\`',- n.nspname,- c.relname,- r.rolname,- act.cmd,- array_agg(p.polname order by p.polname)- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0006_multiple_permissive_policies' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'table'- ) as metadata,- format(- 'multiple_permissive_policies_%s_%s_%s_%s',- n.nspname,- c.relname,- r.rolname,- act.cmd- ) as cache_key-from- pg_catalog.pg_policy p- join pg_catalog.pg_class c- on p.polrelid = c.oid- join pg_catalog.pg_namespace n- on c.relnamespace = n.oid- join pg_catalog.pg_roles r- on p.polroles @> array[r.oid]- or p.polroles = array[0::oid]- left join pg_catalog.pg_depend dep- on c.oid = dep.objid- and dep.deptype = 'e',- lateral (- select x.cmd- from unnest((- select- case p.polcmd- when 'r' then array['SELECT']- when 'a' then array['INSERT']- when 'w' then array['UPDATE']- when 'd' then array['DELETE']- when '*' then array['SELECT', 'INSERT', 'UPDATE', 'DELETE']- else array['ERROR']- end as actions- )) x(cmd)- ) act(cmd)-where- c.relkind = 'r' -- regular tables- and p.polpermissive -- policy is permissive- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and r.rolname not like 'pg_%'- and r.rolname not like 'supabase%admin'- and not r.rolbypassrls- and dep.objid is null -- exclude tables owned by extensions-group by- n.nspname,- c.relname,- r.rolname,- act.cmd-having- count(1) > 1)-union all-(-select- 'policy_exists_rls_disabled' as name,- 'Policy Exists RLS Disabled' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects cases where row level security (RLS) policies have been created, but RLS has not been enabled for the underlying table.' as description,- format(- 'Table \`%s.%s\` has RLS policies but RLS is not enabled on the table. Policies include %s.',- n.nspname,- c.relname,- array_agg(p.polname order by p.polname)- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0007_policy_exists_rls_disabled' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'table'- ) as metadata,- format(- 'policy_exists_rls_disabled_%s_%s',- n.nspname,- c.relname- ) as cache_key-from- pg_catalog.pg_policy p- join pg_catalog.pg_class c- on p.polrelid = c.oid- join pg_catalog.pg_namespace n- on c.relnamespace = n.oid- left join pg_catalog.pg_depend dep- on c.oid = dep.objid- and dep.deptype = 'e'-where- c.relkind = 'r' -- regular tables- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- -- RLS is disabled- and not c.relrowsecurity- and dep.objid is null -- exclude tables owned by extensions-group by- n.nspname,- c.relname)-union all-(-select- 'rls_enabled_no_policy' as name,- 'RLS Enabled No Policy' as title,- 'INFO' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects cases where row level security (RLS) has been enabled on a table but no RLS policies have been created.' as description,- format(- 'Table \`%s.%s\` has RLS enabled, but no policies exist',- n.nspname,- c.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0008_rls_enabled_no_policy' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'table'- ) as metadata,- format(- 'rls_enabled_no_policy_%s_%s',- n.nspname,- c.relname- ) as cache_key-from- pg_catalog.pg_class c- left join pg_catalog.pg_policy p- on p.polrelid = c.oid- join pg_catalog.pg_namespace n- on c.relnamespace = n.oid- left join pg_catalog.pg_depend dep- on c.oid = dep.objid- and dep.deptype = 'e'-where- c.relkind = 'r' -- regular tables- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- -- RLS is enabled- and c.relrowsecurity- and p.polname is null- and dep.objid is null -- exclude tables owned by extensions-group by- n.nspname,- c.relname)-union all-(-select- 'duplicate_index' as name,- 'Duplicate Index' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['PERFORMANCE'] as categories,- 'Detects cases where two ore more identical indexes exist.' as description,- format(- 'Table \`%s.%s\` has identical indexes %s. Drop all except one of them',- n.nspname,- c.relname,- array_agg(pi.indexname order by pi.indexname)- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0009_duplicate_index' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', case- when c.relkind = 'r' then 'table'- when c.relkind = 'm' then 'materialized view'- else 'ERROR'- end,- 'indexes', array_agg(pi.indexname order by pi.indexname)- ) as metadata,- format(- 'duplicate_index_%s_%s_%s',- n.nspname,- c.relname,- array_agg(pi.indexname order by pi.indexname)- ) as cache_key-from- pg_catalog.pg_indexes pi- join pg_catalog.pg_namespace n- on n.nspname = pi.schemaname- join pg_catalog.pg_class c- on pi.tablename = c.relname- and n.oid = c.relnamespace- left join pg_catalog.pg_depend dep- on c.oid = dep.objid- and dep.deptype = 'e'-where- c.relkind in ('r', 'm') -- tables and materialized views- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and dep.objid is null -- exclude tables owned by extensions-group by- n.nspname,- c.relkind,- c.relname,- replace(pi.indexdef, pi.indexname, '')-having- count(*) > 1)-union all-(-select- 'security_definer_view' as name,- 'Security Definer View' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects views defined with the SECURITY DEFINER property. These views enforce Postgres permissions and row level security policies (RLS) of the view creator, rather than that of the querying user' as description,- format(- 'View \`%s.%s\` is defined with the SECURITY DEFINER property',- n.nspname,- c.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0010_security_definer_view' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'view'- ) as metadata,- format(- 'security_definer_view_%s_%s',- n.nspname,- c.relname- ) as cache_key-from- pg_catalog.pg_class c- join pg_catalog.pg_namespace n- on n.oid = c.relnamespace- left join pg_catalog.pg_depend dep- on c.oid = dep.objid- and dep.deptype = 'e'-where- c.relkind = 'v'- and (- pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')- or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')- )- and substring(pg_catalog.version() from 'PostgreSQL ([0-9]+)') >= '15' -- security invoker was added in pg15- and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and dep.objid is null -- exclude views owned by extensions- and not (- lower(coalesce(c.reloptions::text,'{}'))::text[]- && array[- 'security_invoker=1',- 'security_invoker=true',- 'security_invoker=yes',- 'security_invoker=on'- ]- ))-union all-(-select- 'function_search_path_mutable' as name,- 'Function Search Path Mutable' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects functions where the search_path parameter is not set.' as description,- format(- 'Function \`%s.%s\` has a role mutable search_path',- n.nspname,- p.proname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0011_function_search_path_mutable' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', p.proname,- 'type', 'function'- ) as metadata,- format(- 'function_search_path_mutable_%s_%s_%s',- n.nspname,- p.proname,- md5(p.prosrc) -- required when function is polymorphic- ) as cache_key-from- pg_catalog.pg_proc p- join pg_catalog.pg_namespace n- on p.pronamespace = n.oid- left join pg_catalog.pg_depend dep- on p.oid = dep.objid- and dep.deptype = 'e'-where- n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and dep.objid is null -- exclude functions owned by extensions- -- Search path not set- and not exists (- select 1- from unnest(coalesce(p.proconfig, '{}')) as config- where config like 'search_path=%'- ))-union all-(-select- 'rls_disabled_in_public' as name,- 'RLS Disabled in Public' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects cases where row level security (RLS) has not been enabled on tables in schemas exposed to PostgREST' as description,- format(- 'Table \`%s.%s\` is public, but RLS has not been enabled.',- n.nspname,- c.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0013_rls_disabled_in_public' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'table'- ) as metadata,- format(- 'rls_disabled_in_public_%s_%s',- n.nspname,- c.relname- ) as cache_key-from- pg_catalog.pg_class c- join pg_catalog.pg_namespace n- on c.relnamespace = n.oid-where- c.relkind = 'r' -- regular tables- -- RLS is disabled- and not c.relrowsecurity- and (- pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')- or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')- )- and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- ))-union all-(-select- 'extension_in_public' as name,- 'Extension in Public' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects extensions installed in the \`public\` schema.' as description,- format(- 'Extension \`%s\` is installed in the public schema. Move it to another schema.',- pe.extname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0014_extension_in_public' as remediation,- jsonb_build_object(- 'schema', pe.extnamespace::regnamespace,- 'name', pe.extname,- 'type', 'extension'- ) as metadata,- format(- 'extension_in_public_%s',- pe.extname- ) as cache_key-from- pg_catalog.pg_extension pe-where- -- plpgsql is installed by default in public and outside user control- -- confirmed safe- pe.extname not in ('plpgsql')- -- Scoping this to public is not optimal. Ideally we would use the postgres- -- search path. That currently isn't available via SQL. In other lints- -- we have used has_schema_privilege('anon', 'extensions', 'USAGE') but that- -- is not appropriate here as it would evaluate true for the extensions schema- and pe.extnamespace::regnamespace::text = 'public')-union all-(-with policies as (- select- nsp.nspname as schema_name,- pb.tablename as table_name,- polname as policy_name,- qual,- with_check- from- pg_catalog.pg_policy pa- join pg_catalog.pg_class pc- on pa.polrelid = pc.oid- join pg_catalog.pg_namespace nsp- on pc.relnamespace = nsp.oid- join pg_catalog.pg_policies pb- on pc.relname = pb.tablename- and nsp.nspname = pb.schemaname- and pa.polname = pb.policyname-)-select- 'rls_references_user_metadata' as name,- 'RLS references user metadata' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects when Supabase Auth user_metadata is referenced insecurely in a row level security (RLS) policy.' as description,- format(- 'Table \`%s.%s\` has a row level security policy \`%s\` that references Supabase Auth \`user_metadata\`. \`user_metadata\` is editable by end users and should never be used in a security context.',- schema_name,- table_name,- policy_name- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0015_rls_references_user_metadata' as remediation,- jsonb_build_object(- 'schema', schema_name,- 'name', table_name,- 'type', 'table'- ) as metadata,- format('rls_references_user_metadata_%s_%s_%s', schema_name, table_name, policy_name) as cache_key-from- policies-where- schema_name not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and (- -- Example: auth.jwt() -> 'user_metadata'- -- False positives are possible, but it isn't practical to string match- -- If false positive rate is too high, this expression can iterate- qual like '%auth.jwt()%user_metadata%'- or qual like '%current_setting(%request.jwt.claims%)%user_metadata%'- or with_check like '%auth.jwt()%user_metadata%'- or with_check like '%current_setting(%request.jwt.claims%)%user_metadata%'- ))-union all-(-select- 'materialized_view_in_api' as name,- 'Materialized View in API' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects materialized views that are accessible over the Data APIs.' as description,- format(- 'Materialized view \`%s.%s\` is selectable by anon or authenticated roles',- n.nspname,- c.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0016_materialized_view_in_api' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'materialized view'- ) as metadata,- format(- 'materialized_view_in_api_%s_%s',- n.nspname,- c.relname- ) as cache_key-from- pg_catalog.pg_class c- join pg_catalog.pg_namespace n- on n.oid = c.relnamespace- left join pg_catalog.pg_depend dep- on c.oid = dep.objid- and dep.deptype = 'e'-where- c.relkind = 'm'- and (- pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')- or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')- )- and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and dep.objid is null)-union all-(-select- 'foreign_table_in_api' as name,- 'Foreign Table in API' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects foreign tables that are accessible over APIs. Foreign tables do not respect row level security policies.' as description,- format(- 'Foreign table \`%s.%s\` is accessible over APIs',- n.nspname,- c.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0017_foreign_table_in_api' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'foreign table'- ) as metadata,- format(- 'foreign_table_in_api_%s_%s',- n.nspname,- c.relname- ) as cache_key-from- pg_catalog.pg_class c- join pg_catalog.pg_namespace n- on n.oid = c.relnamespace- left join pg_catalog.pg_depend dep- on c.oid = dep.objid- and dep.deptype = 'e'-where- c.relkind = 'f'- and (- pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')- or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')- )- and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- and dep.objid is null)-union all-(-select- 'unsupported_reg_types' as name,- 'Unsupported reg types' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Identifies columns using unsupported reg* types outside pg_catalog schema, which prevents database upgrades using pg_upgrade.' as description,- format(- 'Table \`%s.%s\` has a column \`%s\` with unsupported reg* type \`%s\`.',- n.nspname,- c.relname,- a.attname,- t.typname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=unsupported_reg_types' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'column', a.attname,- 'type', 'table'- ) as metadata,- format(- 'unsupported_reg_types_%s_%s_%s',- n.nspname,- c.relname,- a.attname- ) AS cache_key-from- pg_catalog.pg_attribute a- join pg_catalog.pg_class c- on a.attrelid = c.oid- join pg_catalog.pg_namespace n- on c.relnamespace = n.oid- join pg_catalog.pg_type t- on a.atttypid = t.oid- join pg_catalog.pg_namespace tn- on t.typnamespace = tn.oid-where- tn.nspname = 'pg_catalog'- and t.typname in ('regcollation', 'regconfig', 'regdictionary', 'regnamespace', 'regoper', 'regoperator', 'regproc', 'regprocedure')- and n.nspname not in ('pg_catalog', 'information_schema', 'pgsodium'))-union all-(-select- 'insecure_queue_exposed_in_api' as name,- 'Insecure Queue Exposed in API' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects cases where an insecure Queue is exposed over Data APIs' as description,- format(- 'Table \`%s.%s\` is public, but RLS has not been enabled.',- n.nspname,- c.relname- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0019_insecure_queue_exposed_in_api' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c.relname,- 'type', 'table'- ) as metadata,- format(- 'rls_disabled_in_public_%s_%s',- n.nspname,- c.relname- ) as cache_key-from- pg_catalog.pg_class c- join pg_catalog.pg_namespace n- on c.relnamespace = n.oid-where- c.relkind in ('r', 'I') -- regular or partitioned tables- and not c.relrowsecurity -- RLS is disabled- and (- pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')- or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')- )- and n.nspname = 'pgmq' -- tables in the pgmq schema- and c.relname like 'q_%' -- only queue tables- -- Constant requirements- and 'pgmq_public' = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ','))))))-union all-(-with constants as (- select current_setting('block_size')::numeric as bs, 23 as hdr, 4 as ma-),--bloat_info as (- select- ma,- bs,- schemaname,- tablename,- (datawidth + (hdr + ma - (case when hdr % ma = 0 then ma else hdr % ma end)))::numeric as datahdr,- (maxfracsum * (nullhdr + ma - (case when nullhdr % ma = 0 then ma else nullhdr % ma end))) as nullhdr2- from (- select- schemaname,- tablename,- hdr,- ma,- bs,- sum((1 - null_frac) * avg_width) as datawidth,- max(null_frac) as maxfracsum,- hdr + (- select 1 + count(*) / 8- from pg_stats s2- where- null_frac <> 0- and s2.schemaname = s.schemaname- and s2.tablename = s.tablename- ) as nullhdr- from pg_stats s, constants- group by 1, 2, 3, 4, 5- ) as foo-),--table_bloat as (- select- schemaname,- tablename,- cc.relpages,- bs,- ceil((cc.reltuples * ((datahdr + ma -- (case when datahdr % ma = 0 then ma else datahdr % ma end)) + nullhdr2 + 4)) / (bs - 20::float)) as otta- from- bloat_info- join pg_class cc- on cc.relname = bloat_info.tablename- join pg_namespace nn- on cc.relnamespace = nn.oid- and nn.nspname = bloat_info.schemaname- and nn.nspname <> 'information_schema'- where- cc.relkind = 'r'- and cc.relam = (select oid from pg_am where amname = 'heap')-),--bloat_data as (- select- 'table' as type,- schemaname,- tablename as object_name,- round(case when otta = 0 then 0.0 else table_bloat.relpages / otta::numeric end, 1) as bloat,- case when relpages < otta then 0 else (bs * (table_bloat.relpages - otta)::bigint)::bigint end as raw_waste- from- table_bloat-)--select- 'table_bloat' as name,- 'Table Bloat' as title,- 'INFO' as level,- 'EXTERNAL' as facing,- array['PERFORMANCE'] as categories,- 'Detects if a table has excess bloat and may benefit from maintenance operations like vacuum full or cluster.' as description,- format(- 'Table \`%s\`.\`%s\` has excessive bloat',- bloat_data.schemaname,- bloat_data.object_name- ) as detail,- 'Consider running vacuum full (WARNING: incurs downtime) and tweaking autovacuum settings to reduce bloat.' as remediation,- jsonb_build_object(- 'schema', bloat_data.schemaname,- 'name', bloat_data.object_name,- 'type', bloat_data.type- ) as metadata,- format(- 'table_bloat_%s_%s',- bloat_data.schemaname,- bloat_data.object_name- ) as cache_key-from- bloat_data-where- bloat > 70.0- and raw_waste > (20 * 1024 * 1024) -- filter for waste > 200 MB-order by- schemaname,- object_name)-union all-(-select- 'fkey_to_auth_unique' as name,- 'Foreign Key to Auth Unique Constraint' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects user defined foreign keys to unique constraints in the auth schema.' as description,- format(- 'Table \`%s\`.\`%s\` has a foreign key \`%s\` referencing an auth unique constraint',- n.nspname, -- referencing schema- c_rel.relname, -- referencing table- c.conname -- fkey name- ) as detail,- 'Drop the foreign key constraint that references the auth schema.' as remediation,- jsonb_build_object(- 'schema', n.nspname,- 'name', c_rel.relname,- 'foreign_key', c.conname- ) as metadata,- format(- 'fkey_to_auth_unique_%s_%s_%s',- n.nspname, -- referencing schema- c_rel.relname, -- referencing table- c.conname- ) as cache_key-from- pg_catalog.pg_constraint c- join pg_catalog.pg_class c_rel- on c.conrelid = c_rel.oid- join pg_catalog.pg_namespace n- on c_rel.relnamespace = n.oid- join pg_catalog.pg_class ref_rel- on c.confrelid = ref_rel.oid- join pg_catalog.pg_namespace cn- on ref_rel.relnamespace = cn.oid- join pg_catalog.pg_index i- on c.conindid = i.indexrelid-where c.contype = 'f'- and cn.nspname = 'auth'- and i.indisunique- and not i.indisprimary)-union all-(-select- 'extension_versions_outdated' as name,- 'Extension Versions Outdated' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects extensions that are not using the default (recommended) version.' as description,- format(- 'Extension \`%s\` is using version \`%s\` but version \`%s\` is available. Using outdated extension versions may expose the database to security vulnerabilities.',- ext.name,- ext.installed_version,- ext.default_version- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0022_extension_versions_outdated' as remediation,- jsonb_build_object(- 'extension_name', ext.name,- 'installed_version', ext.installed_version,- 'default_version', ext.default_version- ) as metadata,- format(- 'extension_versions_outdated_%s_%s',- ext.name,- ext.installed_version- ) as cache_key-from- pg_catalog.pg_available_extensions ext-join- -- ignore versions not in pg_available_extension_versions- -- e.g. residue of pg_upgrade- pg_catalog.pg_available_extension_versions extv- on extv.name = ext.name and extv.installed-where- ext.installed_version is not null- and ext.default_version is not null- and ext.installed_version != ext.default_version-order by- ext.name)-union all-(--- Detects tables exposed via API that contain columns with sensitive names--- Inspired by patterns from security scanners that detect PII/credential exposure-with sensitive_patterns as (- select unnest(array[- -- Authentication & Credentials- 'password', 'passwd', 'pwd', 'passphrase',- 'secret', 'secret_key', 'private_key', 'api_key', 'apikey',- 'auth_key', 'token', 'jwt', 'access_token', 'refresh_token',- 'oauth_token', 'session_token', 'bearer_token', 'auth_code',- 'session_id', 'session_key', 'session_secret',- 'recovery_code', 'backup_code', 'verification_code',- 'otp', 'two_factor', '2fa_secret', '2fa_code',- -- Personal Identifiers- 'ssn', 'social_security', 'social_security_number',- 'driver_license', 'drivers_license', 'license_number',- 'passport_number', 'passport_id', 'national_id', 'tax_id',- -- Financial Information- 'credit_card', 'card_number', 'cvv', 'cvc', 'cvn',- 'bank_account', 'account_number', 'routing_number',- 'iban', 'swift_code', 'bic',- -- Health & Medical- 'health_record', 'medical_record', 'patient_id',- 'insurance_number', 'health_insurance', 'medical_insurance',- 'treatment',- -- Device Identifiers- 'mac_address', 'macaddr', 'imei', 'device_uuid',- -- Digital Keys & Certificates- 'pgp_key', 'gpg_key', 'ssh_key', 'certificate',- 'license_key', 'activation_key',- -- Biometric Data- 'facial_recognition'- ]) as pattern-),-exposed_tables as (- select- n.nspname as schema_name,- c.relname as table_name,- c.oid as table_oid- from- pg_catalog.pg_class c- join pg_catalog.pg_namespace n- on c.relnamespace = n.oid- where- c.relkind = 'r' -- regular tables- and (- pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')- or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')- )- and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))- and n.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )- -- Only flag tables without RLS enabled- and not c.relrowsecurity-),-sensitive_columns as (- select- et.schema_name,- et.table_name,- a.attname as column_name,- sp.pattern as matched_pattern- from- exposed_tables et- join pg_catalog.pg_attribute a- on a.attrelid = et.table_oid- and a.attnum > 0- and not a.attisdropped- cross join sensitive_patterns sp- where- -- Match column name against sensitive patterns (case insensitive), allowing '-'/'_' variants- replace(lower(a.attname), '-', '_') = sp.pattern-)-select- 'sensitive_columns_exposed' as name,- 'Sensitive Columns Exposed' as title,- 'ERROR' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects tables exposed via API that contain columns with potentially sensitive data (PII, credentials, financial info) without RLS protection.' as description,- format(- 'Table \`%s.%s\` is exposed via API without RLS and contains potentially sensitive column(s): %s. This may lead to data exposure.',- schema_name,- table_name,- string_agg(distinct column_name, ', ' order by column_name)- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0023_sensitive_columns_exposed' as remediation,- jsonb_build_object(- 'schema', schema_name,- 'name', table_name,- 'type', 'table',- 'sensitive_columns', array_agg(distinct column_name order by column_name),- 'matched_patterns', array_agg(distinct matched_pattern order by matched_pattern)- ) as metadata,- format(- 'sensitive_columns_exposed_%s_%s',- schema_name,- table_name- ) as cache_key-from- sensitive_columns-group by- schema_name,- table_name-order by- schema_name,- table_name)-union all-(--- Detects RLS policies that are overly permissive (e.g., USING (true), USING (1=1))--- These policies effectively disable row-level security while giving a false sense of security-with policies as (- select- nsp.nspname as schema_name,- pb.tablename as table_name,- pc.relrowsecurity as is_rls_active,- pa.polname as policy_name,- pa.polpermissive as is_permissive,- pa.polroles as role_oids,- (select array_agg(r::regrole::text) from unnest(pa.polroles) as x(r)) as roles,- case pa.polcmd- when 'r' then 'SELECT'- when 'a' then 'INSERT'- when 'w' then 'UPDATE'- when 'd' then 'DELETE'- when '*' then 'ALL'- end as command,- pb.qual,- pb.with_check,- -- Normalize expressions by removing whitespace and lowercasing- replace(replace(replace(lower(coalesce(pb.qual, '')), ' ', ''), E'\n', ''), E'\t', '') as normalized_qual,- replace(replace(replace(lower(coalesce(pb.with_check, '')), ' ', ''), E'\n', ''), E'\t', '') as normalized_with_check- from- pg_catalog.pg_policy pa- join pg_catalog.pg_class pc- on pa.polrelid = pc.oid- join pg_catalog.pg_namespace nsp- on pc.relnamespace = nsp.oid- join pg_catalog.pg_policies pb- on pc.relname = pb.tablename- and nsp.nspname = pb.schemaname- and pa.polname = pb.policyname- where- pc.relkind = 'r' -- regular tables- and nsp.nspname not in (- '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'- )-),-permissive_patterns as (- select- p.*,- -- Check for always-true USING clause patterns- -- Note: SELECT with (true) is often intentional and documented, so we only flag UPDATE/DELETE- case when (- command in ('UPDATE', 'DELETE', 'ALL')- and (- normalized_qual in ('true', '(true)', '1=1', '(1=1)')- -- Empty or null qual on permissive policy means allow all- or (qual is null and is_permissive)- )- ) then true else false end as has_permissive_using,- -- Check for always-true WITH CHECK clause patterns- case when (- normalized_with_check in ('true', '(true)', '1=1', '(1=1)')- -- Empty with_check on INSERT means allow all (INSERT has no USING to fall back on)- or (with_check is null and is_permissive and command = 'INSERT')- -- Empty with_check on UPDATE/ALL with permissive USING means allow all writes- or (with_check is null and is_permissive and command in ('UPDATE', 'ALL')- and normalized_qual in ('true', '(true)', '1=1', '(1=1)'))- ) then true else false end as has_permissive_with_check- from- policies p- where- -- Only check tables with RLS enabled (otherwise it's a different lint)- is_rls_active- -- Only check permissive policies (restrictive policies with true are less dangerous)- and is_permissive- -- Only flag policies that apply to anon or authenticated roles (or public/all roles)- and (- role_oids = array[0::oid] -- public (all roles)- or exists (- select 1- from unnest(role_oids) as r- where r::regrole::text in ('anon', 'authenticated')- )- )-)-select- 'rls_policy_always_true' as name,- 'RLS Policy Always True' as title,- 'WARN' as level,- 'EXTERNAL' as facing,- array['SECURITY'] as categories,- 'Detects RLS policies that use overly permissive expressions like \`USING (true)\` or \`WITH CHECK (true)\` for UPDATE, DELETE, or INSERT operations. SELECT policies with \`USING (true)\` are intentionally excluded as this pattern is often used deliberately for public read access.' as description,- format(- 'Table \`%s.%s\` has an RLS policy \`%s\` for \`%s\` that allows unrestricted access%s. This effectively bypasses row-level security for %s.',- schema_name,- table_name,- policy_name,- command,- case- when has_permissive_using and has_permissive_with_check then ' (both USING and WITH CHECK are always true)'- when has_permissive_using then ' (USING clause is always true)'- when has_permissive_with_check then ' (WITH CHECK clause is always true)'- else ''- end,- array_to_string(roles, ', ')- ) as detail,- '${DOCS_URL}/guides/database/database-linter?lint=0024_permissive_rls_policy' as remediation,- jsonb_build_object(- 'schema', schema_name,- 'name', table_name,- 'type', 'table',- 'policy_name', policy_name,- 'command', command,- 'roles', roles,- 'qual', qual,- 'with_check', with_check,- 'permissive_using', has_permissive_using,- 'permissive_with_check', has_permissive_with_check- ) as metadata,- format(- 'rls_policy_always_true_%s_%s_%s',- schema_name,- table_name,- policy_name- ) as cache_key-from- permissive_patterns-where- has_permissive_using or has_permissive_with_check-order by- schema_name,- table_name,- policy_name)`.trim()diff --git a/apps/studio/lib/integration-utils.ts b/apps/studio/lib/integration-utils.tsindex 49a6d89f13e..f113d798654 100644--- a/apps/studio/lib/integration-utils.ts+++ b/apps/studio/lib/integration-utils.ts@@ -1,6 +1,8 @@+import { getCreateMigrationsTableSQL, getInsertMigrationSQL } from '@supabase/pg-meta'import { fetchHandler } from 'data/fetchers'import type { Integration } from 'data/integrations/integrations.types'import { ResponseError, type SupaResponse } from 'types'+import { isResponseOk } from './api/apiWrapper'async function fetchGitHub<T = any>(url: string, responseJson = true): Promise<SupaResponse<T>> {@@ -76,13 +78,10 @@ export async function getInitialMigrationSQLFromGitHubRepo(const migrations = migrationFileResponses.filter((response) => isResponseOk(response)).join(';')const seed = isResponseOk(seedFileResponse) ? seedFileResponse : ''- const migrationsTableSql = /* SQL */ `- create schema if not exists supabase_migrations;- create table if not exists supabase_migrations.schema_migrations (- version text not null primary key,- statements text[],- name text- );+ const createMigrationsTableSql = getCreateMigrationsTableSQL()++ const migrationsTableSql = `+ ${createMigrationsTableSql}${sortedFiles.map((file, i) => {const migration = migrationFileResponses[i]@@ -95,12 +94,7 @@ export async function getInitialMigrationSQLFromGitHubRepo(.map((statement) => statement.trim()).filter(Boolean))-- return /* SQL */ `- insert into supabase_migrations.schema_migrations (version, statements, name)- select '${version}', array_agg(jsonb_statements)::text[], '${file.name}'- from jsonb_array_elements_text($statements$${statements}$statements$::jsonb) as jsonb_statements;- `+ return getInsertMigrationSQL({ name: file.name, version, statements })}).join('')}`diff --git a/apps/studio/lib/role-impersonation.ts b/apps/studio/lib/role-impersonation.tsindex 132286b47ca..ed84de53f01 100644--- a/apps/studio/lib/role-impersonation.ts+++ b/apps/studio/lib/role-impersonation.ts@@ -1,4 +1,4 @@-import { ident, literal } from '@supabase/pg-meta/src/pg-format'+import { getImpersonationSQL } from '@supabase/pg-meta'import type { User } from 'data/auth/users-infinite-query'import { RoleImpersonationState as ValtioRoleImpersonationState } from 'state/role-impersonation-state'@@ -33,7 +33,7 @@ type PostgrestImpersonationRole =export type PostgrestRole = PostgrestImpersonationRole['role']-export type CustomImpersonationRole = {+type CustomImpersonationRole = {type: 'custom'role: string}@@ -94,56 +94,17 @@ export function getPostgrestClaims(projectRef: string, role: PostgrestImpersonat}}-function getPostgrestRoleImpersonationSql(- role: PostgrestImpersonationRole,- claims: ReturnType<typeof getPostgrestClaims>-) {- const unexpiredClaims = { ...claims, exp: getExp1HourFromNow() }-- return `-select set_config('role', ${literal(role.role)}, true),-set_config('request.jwt.claims', ${literal(JSON.stringify(unexpiredClaims))}, true),-set_config('request.method', 'POST', true),-set_config('request.path', '/impersonation-example-request-path', true),-set_config('request.headers', '{"accept": "*/*"}', true);- `.trim()-}--// Includes getPostgrestRoleImpersonationSql() and wrapWithRoleImpersonation()-export const ROLE_IMPERSONATION_SQL_LINE_COUNT = 11-export const ROLE_IMPERSONATION_NO_RESULTS = 'ROLE_IMPERSONATION_NO_RESULTS'--function getCustomRoleImpersonationSql(roleName: string) {- return /* SQL */ `- set local role ${literal(roleName)};- `.trim()-}-export type RoleImpersonationState = Pick<ValtioRoleImpersonationState, 'role' | 'claims'>export function wrapWithRoleImpersonation(sql: string, state?: RoleImpersonationState) {const { role, claims } = state ?? { role: undefined, claims: undefined }- if (role === undefined) {- return sql- }-- const impersonationSql =- role.type === 'postgrest'- ? claims !== undefined- ? getPostgrestRoleImpersonationSql(role, claims)- : ''- : getCustomRoleImpersonationSql(role.role)-- return /* SQL */ `- ${impersonationSql}-- -- If the users sql returns no rows, pg-meta will- -- fallback to returning the result of the impersonation sql.- select 1 as "${ROLE_IMPERSONATION_NO_RESULTS}";+ if (role === undefined) return sql- ${sql}- `.trim()+ const unexpiredClaims =+ claims !== undefined ? { ...claims, exp: getExp1HourFromNow() } : undefined+ const impersonationSql = getImpersonationSQL({ role: role, unexpiredClaims, sql })+ return impersonationSql}function encodeText(data: string) {diff --git a/packages/pg-meta/src/index.ts b/packages/pg-meta/src/index.tsindex 6035d5789da..aaab8e5355e 100644--- a/packages/pg-meta/src/index.ts+++ b/packages/pg-meta/src/index.ts@@ -30,6 +30,7 @@ export * from './sql/studio/storage'export * from './sql/studio/database'export * from './sql/studio/table-editor'export * from './sql/studio/sql-editor'+export * from './sql/studio/role-impersonation'export default {roles,diff --git a/packages/pg-meta/src/query/Query.utils.ts b/packages/pg-meta/src/query/Query.utils.tsindex 5a4af7e305d..5f920bc77fc 100644--- a/packages/pg-meta/src/query/Query.utils.ts+++ b/packages/pg-meta/src/query/Query.utils.ts@@ -313,3 +313,23 @@ function queryTable(table: QueryTable) {function queryCTE(table: QueryTable) {return `${ident(table.name)}`}++export function wrapWithTransaction(sql: string) {+ return /* SQL */ `+ begin;++ ${sql}++ commit;+ `+}++export function wrapWithRollback(sql: string) {+ return /* SQL */ `+ begin;++ ${sql}++ rollback;+ `+}diff --git a/packages/pg-meta/src/sql/studio/advisor/index.ts b/packages/pg-meta/src/sql/studio/advisor/index.tsindex 1bc3b58c74e..6e1f6f83bb3 100644--- a/packages/pg-meta/src/sql/studio/advisor/index.ts+++ b/packages/pg-meta/src/sql/studio/advisor/index.ts@@ -1 +1,2 @@export * from './index-advisor'+export * from './lints'diff --git a/packages/pg-meta/src/sql/studio/advisor/lints.ts b/packages/pg-meta/src/sql/studio/advisor/lints.tsnew file mode 100644index 00000000000..dbd155ea77f--- /dev/null+++ b/packages/pg-meta/src/sql/studio/advisor/lints.ts@@ -0,0 +1,1411 @@+export const enrichLintsQuery = (query: string, exposedSchemas?: string) => {+ return `+do $$+begin+ set pg_stat_statements.track = none;+exception when others then+ -- not a superuser or extension not installed, skip silently+end+$$;+${!!exposedSchemas ? `set local pgrst.db_schemas = '${exposedSchemas}';` : ''}+-- source: dashboard+-- user: ${'self host'}+-- date: ${new Date().toISOString()}++${query}+`+}++/**+ * Pulled from https://github.com/supabase/splinter/blob/main/splinter.sql+ * Things to do after copy pasting from splinter.sql+ * - Replace all "\`%s\`" with backquotes to escape the tick character ("\`%s\`")+ * - Replace docs url with docsUrl (${docsUrl})+ */+export const getLintsSQL = ({ docsUrl }: { docsUrl: string }) =>+ /* SQL */ `set local search_path = '';++(+with foreign_keys as (+ select+ cl.relnamespace::regnamespace::text as schema_name,+ cl.relname as table_name,+ cl.oid as table_oid,+ ct.conname as fkey_name,+ ct.conkey as col_attnums+ from+ pg_catalog.pg_constraint ct+ join pg_catalog.pg_class cl -- fkey owning table+ on ct.conrelid = cl.oid+ left join pg_catalog.pg_depend d+ on d.objid = cl.oid+ and d.deptype = 'e'+ where+ ct.contype = 'f' -- foreign key constraints+ and d.objid is null -- exclude tables that are dependencies of extensions+ and cl.relnamespace::regnamespace::text not in (+ 'pg_catalog', 'information_schema', 'auth', 'storage', 'vault', 'extensions'+ )+),+index_ as (+ select+ pi.indrelid as table_oid,+ indexrelid::regclass as index_,+ string_to_array(indkey::text, ' ')::smallint[] as col_attnums+ from+ pg_catalog.pg_index pi+ where+ indisvalid+)+select+ 'unindexed_foreign_keys' as name,+ 'Unindexed foreign keys' as title,+ 'INFO' as level,+ 'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,+ 'Identifies foreign key constraints without a covering index, which can impact database performance.' as description,+ format(+ 'Table \`%s.%s\` has a foreign key \`%s\` without a covering index. This can lead to suboptimal query performance.',+ fk.schema_name,+ fk.table_name,+ fk.fkey_name+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0001_unindexed_foreign_keys' as remediation,+ jsonb_build_object(+ 'schema', fk.schema_name,+ 'name', fk.table_name,+ 'type', 'table',+ 'fkey_name', fk.fkey_name,+ 'fkey_columns', fk.col_attnums+ ) as metadata,+ format('unindexed_foreign_keys_%s_%s_%s', fk.schema_name, fk.table_name, fk.fkey_name) as cache_key+from+ foreign_keys fk+ left join index_ idx+ on fk.table_oid = idx.table_oid+ and fk.col_attnums = idx.col_attnums[1:array_length(fk.col_attnums, 1)]+ left join pg_catalog.pg_depend dep+ on idx.table_oid = dep.objid+ and dep.deptype = 'e'+where+ idx.index_ is null+ and fk.schema_name not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and dep.objid is null -- exclude tables owned by extensions+order by+ fk.schema_name,+ fk.table_name,+ fk.fkey_name)+union all+(+select+ 'auth_users_exposed' as name,+ 'Exposed Auth Users' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects if auth.users is exposed to anon or authenticated roles via a view or materialized view in schemas exposed to PostgREST, potentially compromising user data security.' as description,+ format(+ 'View/Materialized View "%s" in the public schema may expose \`auth.users\` data to anon or authenticated roles.',+ c.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0002_auth_users_exposed' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'view',+ 'exposed_to', array_remove(array_agg(DISTINCT case when pg_catalog.has_table_privilege('anon', c.oid, 'SELECT') then 'anon' when pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT') then 'authenticated' end), null)+ ) as metadata,+ format('auth_users_exposed_%s_%s', n.nspname, c.relname) as cache_key+from+ -- Identify the oid for auth.users+ pg_catalog.pg_class auth_users_pg_class+ join pg_catalog.pg_namespace auth_users_pg_namespace+ on auth_users_pg_class.relnamespace = auth_users_pg_namespace.oid+ and auth_users_pg_class.relname = 'users'+ and auth_users_pg_namespace.nspname = 'auth'+ -- Depends on auth.users+ join pg_catalog.pg_depend d+ on d.refobjid = auth_users_pg_class.oid+ join pg_catalog.pg_rewrite r+ on r.oid = d.objid+ join pg_catalog.pg_class c+ on c.oid = r.ev_class+ join pg_catalog.pg_namespace n+ on n.oid = c.relnamespace+ join pg_catalog.pg_class pg_class_auth_users+ on d.refobjid = pg_class_auth_users.oid+where+ d.deptype = 'n'+ and (+ pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')+ or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')+ )+ and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))+ -- Exclude self+ and c.relname <> '0002_auth_users_exposed'+ -- There are 3 insecure configurations+ and+ (+ -- Materialized views don't support RLS so this is insecure by default+ (c.relkind in ('m')) -- m for materialized view+ or+ -- Standard View, accessible to anon or authenticated that is security_definer+ (+ c.relkind = 'v' -- v for view+ -- Exclude security invoker views+ and not (+ lower(coalesce(c.reloptions::text,'{}'))::text[]+ && array[+ 'security_invoker=1',+ 'security_invoker=true',+ 'security_invoker=yes',+ 'security_invoker=on'+ ]+ )+ )+ or+ -- Standard View, security invoker, but no RLS enabled on auth.users+ (+ c.relkind in ('v') -- v for view+ -- is security invoker+ and (+ lower(coalesce(c.reloptions::text,'{}'))::text[]+ && array[+ 'security_invoker=1',+ 'security_invoker=true',+ 'security_invoker=yes',+ 'security_invoker=on'+ ]+ )+ and not pg_class_auth_users.relrowsecurity+ )+ )+group by+ n.nspname,+ c.relname,+ c.oid)+union all+(+with policies as (+ select+ nsp.nspname as schema_name,+ pb.tablename as table_name,+ pc.relrowsecurity as is_rls_active,+ polname as policy_name,+ polpermissive as is_permissive, -- if not, then restrictive+ (select array_agg(r::regrole) from unnest(polroles) as x(r)) as roles,+ case polcmd+ when 'r' then 'SELECT'+ when 'a' then 'INSERT'+ when 'w' then 'UPDATE'+ when 'd' then 'DELETE'+ when '*' then 'ALL'+ end as command,+ qual,+ with_check+ from+ pg_catalog.pg_policy pa+ join pg_catalog.pg_class pc+ on pa.polrelid = pc.oid+ join pg_catalog.pg_namespace nsp+ on pc.relnamespace = nsp.oid+ join pg_catalog.pg_policies pb+ on pc.relname = pb.tablename+ and nsp.nspname = pb.schemaname+ and pa.polname = pb.policyname+)+select+ 'auth_rls_initplan' as name,+ 'Auth RLS Initialization Plan' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,+ 'Detects if calls to \`current_setting()\` and \`auth.<function>()\` in RLS policies are being unnecessarily re-evaluated for each row' as description,+ format(+ 'Table \`%s.%s\` has a row level security policy \`%s\` that re-evaluates current_setting() or auth.<function>() for each row. This produces suboptimal query performance at scale. Resolve the issue by replacing \`auth.<function>()\` with \`(select auth.<function>())\`. See [docs](${docsUrl}/guides/database/postgres/row-level-security#call-functions-with-select) for more info.',+ schema_name,+ table_name,+ policy_name+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0003_auth_rls_initplan' as remediation,+ jsonb_build_object(+ 'schema', schema_name,+ 'name', table_name,+ 'type', 'table'+ ) as metadata,+ format('auth_rls_init_plan_%s_%s_%s', schema_name, table_name, policy_name) as cache_key+from+ policies+where+ is_rls_active+ -- NOTE: does not include realtime in support of monitoring policies on realtime.messages+ and schema_name not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and (+ -- Example: auth.uid()+ (+ qual like '%auth.uid()%'+ and lower(qual) not like '%select auth.uid()%'+ )+ or (+ qual like '%auth.jwt()%'+ and lower(qual) not like '%select auth.jwt()%'+ )+ or (+ qual like '%auth.role()%'+ and lower(qual) not like '%select auth.role()%'+ )+ or (+ qual like '%auth.email()%'+ and lower(qual) not like '%select auth.email()%'+ )+ or (+ qual like '%current\_setting(%)%'+ and lower(qual) not like '%select current\_setting(%)%'+ )+ or (+ with_check like '%auth.uid()%'+ and lower(with_check) not like '%select auth.uid()%'+ )+ or (+ with_check like '%auth.jwt()%'+ and lower(with_check) not like '%select auth.jwt()%'+ )+ or (+ with_check like '%auth.role()%'+ and lower(with_check) not like '%select auth.role()%'+ )+ or (+ with_check like '%auth.email()%'+ and lower(with_check) not like '%select auth.email()%'+ )+ or (+ with_check like '%current\_setting(%)%'+ and lower(with_check) not like '%select current\_setting(%)%'+ )+ ))+union all+(+select+ 'no_primary_key' as name,+ 'No Primary Key' as title,+ 'INFO' as level,+ 'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,+ 'Detects if a table does not have a primary key. Tables without a primary key can be inefficient to interact with at scale.' as description,+ format(+ 'Table \`%s.%s\` does not have a primary key',+ pgns.nspname,+ pgc.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0004_no_primary_key' as remediation,+ jsonb_build_object(+ 'schema', pgns.nspname,+ 'name', pgc.relname,+ 'type', 'table'+ ) as metadata,+ format(+ 'no_primary_key_%s_%s',+ pgns.nspname,+ pgc.relname+ ) as cache_key+from+ pg_catalog.pg_class pgc+ join pg_catalog.pg_namespace pgns+ on pgns.oid = pgc.relnamespace+ left join pg_catalog.pg_index pgi+ on pgi.indrelid = pgc.oid+ left join pg_catalog.pg_depend dep+ on pgc.oid = dep.objid+ and dep.deptype = 'e'+where+ pgc.relkind = 'r' -- regular tables+ and pgns.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and dep.objid is null -- exclude tables owned by extensions+group by+ pgc.oid,+ pgns.nspname,+ pgc.relname+having+ max(coalesce(pgi.indisprimary, false)::int) = 0)+union all+(+select+ 'unused_index' as name,+ 'Unused Index' as title,+ 'INFO' as level,+ 'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,+ 'Detects if an index has never been used and may be a candidate for removal.' as description,+ format(+ 'Index \`%s\` on table \`%s.%s\` has not been used',+ psui.indexrelname,+ psui.schemaname,+ psui.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0005_unused_index' as remediation,+ jsonb_build_object(+ 'schema', psui.schemaname,+ 'name', psui.relname,+ 'type', 'table'+ ) as metadata,+ format(+ 'unused_index_%s_%s_%s',+ psui.schemaname,+ psui.relname,+ psui.indexrelname+ ) as cache_key++from+ pg_catalog.pg_stat_user_indexes psui+ join pg_catalog.pg_index pi+ on psui.indexrelid = pi.indexrelid+ left join pg_catalog.pg_depend dep+ on psui.relid = dep.objid+ and dep.deptype = 'e'+where+ psui.idx_scan = 0+ and not pi.indisunique+ and not pi.indisprimary+ and dep.objid is null -- exclude tables owned by extensions+ and psui.schemaname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ ))+union all+(+select+ 'multiple_permissive_policies' as name,+ 'Multiple Permissive Policies' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,+ 'Detects if multiple permissive row level security policies are present on a table for the same \`role\` and \`action\` (e.g. insert). Multiple permissive policies are suboptimal for performance as each policy must be executed for every relevant query.' as description,+ format(+ 'Table \`%s.%s\` has multiple permissive policies for role \`%s\` for action \`%s\`. Policies include \`%s\`',+ n.nspname,+ c.relname,+ r.rolname,+ act.cmd,+ array_agg(p.polname order by p.polname)+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0006_multiple_permissive_policies' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'table'+ ) as metadata,+ format(+ 'multiple_permissive_policies_%s_%s_%s_%s',+ n.nspname,+ c.relname,+ r.rolname,+ act.cmd+ ) as cache_key+from+ pg_catalog.pg_policy p+ join pg_catalog.pg_class c+ on p.polrelid = c.oid+ join pg_catalog.pg_namespace n+ on c.relnamespace = n.oid+ join pg_catalog.pg_roles r+ on p.polroles @> array[r.oid]+ or p.polroles = array[0::oid]+ left join pg_catalog.pg_depend dep+ on c.oid = dep.objid+ and dep.deptype = 'e',+ lateral (+ select x.cmd+ from unnest((+ select+ case p.polcmd+ when 'r' then array['SELECT']+ when 'a' then array['INSERT']+ when 'w' then array['UPDATE']+ when 'd' then array['DELETE']+ when '*' then array['SELECT', 'INSERT', 'UPDATE', 'DELETE']+ else array['ERROR']+ end as actions+ )) x(cmd)+ ) act(cmd)+where+ c.relkind = 'r' -- regular tables+ and p.polpermissive -- policy is permissive+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and r.rolname not like 'pg_%'+ and r.rolname not like 'supabase%admin'+ and not r.rolbypassrls+ and dep.objid is null -- exclude tables owned by extensions+group by+ n.nspname,+ c.relname,+ r.rolname,+ act.cmd+having+ count(1) > 1)+union all+(+select+ 'policy_exists_rls_disabled' as name,+ 'Policy Exists RLS Disabled' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects cases where row level security (RLS) policies have been created, but RLS has not been enabled for the underlying table.' as description,+ format(+ 'Table \`%s.%s\` has RLS policies but RLS is not enabled on the table. Policies include %s.',+ n.nspname,+ c.relname,+ array_agg(p.polname order by p.polname)+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0007_policy_exists_rls_disabled' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'table'+ ) as metadata,+ format(+ 'policy_exists_rls_disabled_%s_%s',+ n.nspname,+ c.relname+ ) as cache_key+from+ pg_catalog.pg_policy p+ join pg_catalog.pg_class c+ on p.polrelid = c.oid+ join pg_catalog.pg_namespace n+ on c.relnamespace = n.oid+ left join pg_catalog.pg_depend dep+ on c.oid = dep.objid+ and dep.deptype = 'e'+where+ c.relkind = 'r' -- regular tables+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ -- RLS is disabled+ and not c.relrowsecurity+ and dep.objid is null -- exclude tables owned by extensions+group by+ n.nspname,+ c.relname)+union all+(+select+ 'rls_enabled_no_policy' as name,+ 'RLS Enabled No Policy' as title,+ 'INFO' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects cases where row level security (RLS) has been enabled on a table but no RLS policies have been created.' as description,+ format(+ 'Table \`%s.%s\` has RLS enabled, but no policies exist',+ n.nspname,+ c.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0008_rls_enabled_no_policy' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'table'+ ) as metadata,+ format(+ 'rls_enabled_no_policy_%s_%s',+ n.nspname,+ c.relname+ ) as cache_key+from+ pg_catalog.pg_class c+ left join pg_catalog.pg_policy p+ on p.polrelid = c.oid+ join pg_catalog.pg_namespace n+ on c.relnamespace = n.oid+ left join pg_catalog.pg_depend dep+ on c.oid = dep.objid+ and dep.deptype = 'e'+where+ c.relkind = 'r' -- regular tables+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ -- RLS is enabled+ and c.relrowsecurity+ and p.polname is null+ and dep.objid is null -- exclude tables owned by extensions+group by+ n.nspname,+ c.relname)+union all+(+select+ 'duplicate_index' as name,+ 'Duplicate Index' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,+ 'Detects cases where two ore more identical indexes exist.' as description,+ format(+ 'Table \`%s.%s\` has identical indexes %s. Drop all except one of them',+ n.nspname,+ c.relname,+ array_agg(pi.indexname order by pi.indexname)+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0009_duplicate_index' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', case+ when c.relkind = 'r' then 'table'+ when c.relkind = 'm' then 'materialized view'+ else 'ERROR'+ end,+ 'indexes', array_agg(pi.indexname order by pi.indexname)+ ) as metadata,+ format(+ 'duplicate_index_%s_%s_%s',+ n.nspname,+ c.relname,+ array_agg(pi.indexname order by pi.indexname)+ ) as cache_key+from+ pg_catalog.pg_indexes pi+ join pg_catalog.pg_namespace n+ on n.nspname = pi.schemaname+ join pg_catalog.pg_class c+ on pi.tablename = c.relname+ and n.oid = c.relnamespace+ left join pg_catalog.pg_depend dep+ on c.oid = dep.objid+ and dep.deptype = 'e'+where+ c.relkind in ('r', 'm') -- tables and materialized views+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and dep.objid is null -- exclude tables owned by extensions+group by+ n.nspname,+ c.relkind,+ c.relname,+ replace(pi.indexdef, pi.indexname, '')+having+ count(*) > 1)+union all+(+select+ 'security_definer_view' as name,+ 'Security Definer View' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects views defined with the SECURITY DEFINER property. These views enforce Postgres permissions and row level security policies (RLS) of the view creator, rather than that of the querying user' as description,+ format(+ 'View \`%s.%s\` is defined with the SECURITY DEFINER property',+ n.nspname,+ c.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0010_security_definer_view' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'view'+ ) as metadata,+ format(+ 'security_definer_view_%s_%s',+ n.nspname,+ c.relname+ ) as cache_key+from+ pg_catalog.pg_class c+ join pg_catalog.pg_namespace n+ on n.oid = c.relnamespace+ left join pg_catalog.pg_depend dep+ on c.oid = dep.objid+ and dep.deptype = 'e'+where+ c.relkind = 'v'+ and (+ pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')+ or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')+ )+ and substring(pg_catalog.version() from 'PostgreSQL ([0-9]+)') >= '15' -- security invoker was added in pg15+ and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and dep.objid is null -- exclude views owned by extensions+ and not (+ lower(coalesce(c.reloptions::text,'{}'))::text[]+ && array[+ 'security_invoker=1',+ 'security_invoker=true',+ 'security_invoker=yes',+ 'security_invoker=on'+ ]+ ))+union all+(+select+ 'function_search_path_mutable' as name,+ 'Function Search Path Mutable' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects functions where the search_path parameter is not set.' as description,+ format(+ 'Function \`%s.%s\` has a role mutable search_path',+ n.nspname,+ p.proname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0011_function_search_path_mutable' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', p.proname,+ 'type', 'function'+ ) as metadata,+ format(+ 'function_search_path_mutable_%s_%s_%s',+ n.nspname,+ p.proname,+ md5(p.prosrc) -- required when function is polymorphic+ ) as cache_key+from+ pg_catalog.pg_proc p+ join pg_catalog.pg_namespace n+ on p.pronamespace = n.oid+ left join pg_catalog.pg_depend dep+ on p.oid = dep.objid+ and dep.deptype = 'e'+where+ n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and dep.objid is null -- exclude functions owned by extensions+ -- Search path not set+ and not exists (+ select 1+ from unnest(coalesce(p.proconfig, '{}')) as config+ where config like 'search_path=%'+ ))+union all+(+select+ 'rls_disabled_in_public' as name,+ 'RLS Disabled in Public' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects cases where row level security (RLS) has not been enabled on tables in schemas exposed to PostgREST' as description,+ format(+ 'Table \`%s.%s\` is public, but RLS has not been enabled.',+ n.nspname,+ c.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0013_rls_disabled_in_public' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'table'+ ) as metadata,+ format(+ 'rls_disabled_in_public_%s_%s',+ n.nspname,+ c.relname+ ) as cache_key+from+ pg_catalog.pg_class c+ join pg_catalog.pg_namespace n+ on c.relnamespace = n.oid+where+ c.relkind = 'r' -- regular tables+ -- RLS is disabled+ and not c.relrowsecurity+ and (+ pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')+ or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')+ )+ and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ ))+union all+(+select+ 'extension_in_public' as name,+ 'Extension in Public' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects extensions installed in the \`public\` schema.' as description,+ format(+ 'Extension \`%s\` is installed in the public schema. Move it to another schema.',+ pe.extname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0014_extension_in_public' as remediation,+ jsonb_build_object(+ 'schema', pe.extnamespace::regnamespace,+ 'name', pe.extname,+ 'type', 'extension'+ ) as metadata,+ format(+ 'extension_in_public_%s',+ pe.extname+ ) as cache_key+from+ pg_catalog.pg_extension pe+where+ -- plpgsql is installed by default in public and outside user control+ -- confirmed safe+ pe.extname not in ('plpgsql')+ -- Scoping this to public is not optimal. Ideally we would use the postgres+ -- search path. That currently isn't available via SQL. In other lints+ -- we have used has_schema_privilege('anon', 'extensions', 'USAGE') but that+ -- is not appropriate here as it would evaluate true for the extensions schema+ and pe.extnamespace::regnamespace::text = 'public')+union all+(+with policies as (+ select+ nsp.nspname as schema_name,+ pb.tablename as table_name,+ polname as policy_name,+ qual,+ with_check+ from+ pg_catalog.pg_policy pa+ join pg_catalog.pg_class pc+ on pa.polrelid = pc.oid+ join pg_catalog.pg_namespace nsp+ on pc.relnamespace = nsp.oid+ join pg_catalog.pg_policies pb+ on pc.relname = pb.tablename+ and nsp.nspname = pb.schemaname+ and pa.polname = pb.policyname+)+select+ 'rls_references_user_metadata' as name,+ 'RLS references user metadata' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects when Supabase Auth user_metadata is referenced insecurely in a row level security (RLS) policy.' as description,+ format(+ 'Table \`%s.%s\` has a row level security policy \`%s\` that references Supabase Auth \`user_metadata\`. \`user_metadata\` is editable by end users and should never be used in a security context.',+ schema_name,+ table_name,+ policy_name+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0015_rls_references_user_metadata' as remediation,+ jsonb_build_object(+ 'schema', schema_name,+ 'name', table_name,+ 'type', 'table'+ ) as metadata,+ format('rls_references_user_metadata_%s_%s_%s', schema_name, table_name, policy_name) as cache_key+from+ policies+where+ schema_name not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and (+ -- Example: auth.jwt() -> 'user_metadata'+ -- False positives are possible, but it isn't practical to string match+ -- If false positive rate is too high, this expression can iterate+ qual like '%auth.jwt()%user_metadata%'+ or qual like '%current_setting(%request.jwt.claims%)%user_metadata%'+ or with_check like '%auth.jwt()%user_metadata%'+ or with_check like '%current_setting(%request.jwt.claims%)%user_metadata%'+ ))+union all+(+select+ 'materialized_view_in_api' as name,+ 'Materialized View in API' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects materialized views that are accessible over the Data APIs.' as description,+ format(+ 'Materialized view \`%s.%s\` is selectable by anon or authenticated roles',+ n.nspname,+ c.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0016_materialized_view_in_api' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'materialized view'+ ) as metadata,+ format(+ 'materialized_view_in_api_%s_%s',+ n.nspname,+ c.relname+ ) as cache_key+from+ pg_catalog.pg_class c+ join pg_catalog.pg_namespace n+ on n.oid = c.relnamespace+ left join pg_catalog.pg_depend dep+ on c.oid = dep.objid+ and dep.deptype = 'e'+where+ c.relkind = 'm'+ and (+ pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')+ or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')+ )+ and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and dep.objid is null)+union all+(+select+ 'foreign_table_in_api' as name,+ 'Foreign Table in API' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects foreign tables that are accessible over APIs. Foreign tables do not respect row level security policies.' as description,+ format(+ 'Foreign table \`%s.%s\` is accessible over APIs',+ n.nspname,+ c.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0017_foreign_table_in_api' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'foreign table'+ ) as metadata,+ format(+ 'foreign_table_in_api_%s_%s',+ n.nspname,+ c.relname+ ) as cache_key+from+ pg_catalog.pg_class c+ join pg_catalog.pg_namespace n+ on n.oid = c.relnamespace+ left join pg_catalog.pg_depend dep+ on c.oid = dep.objid+ and dep.deptype = 'e'+where+ c.relkind = 'f'+ and (+ pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')+ or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')+ )+ and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ and dep.objid is null)+union all+(+select+ 'unsupported_reg_types' as name,+ 'Unsupported reg types' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Identifies columns using unsupported reg* types outside pg_catalog schema, which prevents database upgrades using pg_upgrade.' as description,+ format(+ 'Table \`%s.%s\` has a column \`%s\` with unsupported reg* type \`%s\`.',+ n.nspname,+ c.relname,+ a.attname,+ t.typname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=unsupported_reg_types' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'column', a.attname,+ 'type', 'table'+ ) as metadata,+ format(+ 'unsupported_reg_types_%s_%s_%s',+ n.nspname,+ c.relname,+ a.attname+ ) AS cache_key+from+ pg_catalog.pg_attribute a+ join pg_catalog.pg_class c+ on a.attrelid = c.oid+ join pg_catalog.pg_namespace n+ on c.relnamespace = n.oid+ join pg_catalog.pg_type t+ on a.atttypid = t.oid+ join pg_catalog.pg_namespace tn+ on t.typnamespace = tn.oid+where+ tn.nspname = 'pg_catalog'+ and t.typname in ('regcollation', 'regconfig', 'regdictionary', 'regnamespace', 'regoper', 'regoperator', 'regproc', 'regprocedure')+ and n.nspname not in ('pg_catalog', 'information_schema', 'pgsodium'))+union all+(+select+ 'insecure_queue_exposed_in_api' as name,+ 'Insecure Queue Exposed in API' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects cases where an insecure Queue is exposed over Data APIs' as description,+ format(+ 'Table \`%s.%s\` is public, but RLS has not been enabled.',+ n.nspname,+ c.relname+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0019_insecure_queue_exposed_in_api' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c.relname,+ 'type', 'table'+ ) as metadata,+ format(+ 'rls_disabled_in_public_%s_%s',+ n.nspname,+ c.relname+ ) as cache_key+from+ pg_catalog.pg_class c+ join pg_catalog.pg_namespace n+ on c.relnamespace = n.oid+where+ c.relkind in ('r', 'I') -- regular or partitioned tables+ and not c.relrowsecurity -- RLS is disabled+ and (+ pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')+ or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')+ )+ and n.nspname = 'pgmq' -- tables in the pgmq schema+ and c.relname like 'q_%' -- only queue tables+ -- Constant requirements+ and 'pgmq_public' = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ','))))))+union all+(+with constants as (+ select current_setting('block_size')::numeric as bs, 23 as hdr, 4 as ma+),++bloat_info as (+ select+ ma,+ bs,+ schemaname,+ tablename,+ (datawidth + (hdr + ma - (case when hdr % ma = 0 then ma else hdr % ma end)))::numeric as datahdr,+ (maxfracsum * (nullhdr + ma - (case when nullhdr % ma = 0 then ma else nullhdr % ma end))) as nullhdr2+ from (+ select+ schemaname,+ tablename,+ hdr,+ ma,+ bs,+ sum((1 - null_frac) * avg_width) as datawidth,+ max(null_frac) as maxfracsum,+ hdr + (+ select 1 + count(*) / 8+ from pg_stats s2+ where+ null_frac <> 0+ and s2.schemaname = s.schemaname+ and s2.tablename = s.tablename+ ) as nullhdr+ from pg_stats s, constants+ group by 1, 2, 3, 4, 5+ ) as foo+),++table_bloat as (+ select+ schemaname,+ tablename,+ cc.relpages,+ bs,+ ceil((cc.reltuples * ((datahdr + ma -+ (case when datahdr % ma = 0 then ma else datahdr % ma end)) + nullhdr2 + 4)) / (bs - 20::float)) as otta+ from+ bloat_info+ join pg_class cc+ on cc.relname = bloat_info.tablename+ join pg_namespace nn+ on cc.relnamespace = nn.oid+ and nn.nspname = bloat_info.schemaname+ and nn.nspname <> 'information_schema'+ where+ cc.relkind = 'r'+ and cc.relam = (select oid from pg_am where amname = 'heap')+),++bloat_data as (+ select+ 'table' as type,+ schemaname,+ tablename as object_name,+ round(case when otta = 0 then 0.0 else table_bloat.relpages / otta::numeric end, 1) as bloat,+ case when relpages < otta then 0 else (bs * (table_bloat.relpages - otta)::bigint)::bigint end as raw_waste+ from+ table_bloat+)++select+ 'table_bloat' as name,+ 'Table Bloat' as title,+ 'INFO' as level,+ 'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,+ 'Detects if a table has excess bloat and may benefit from maintenance operations like vacuum full or cluster.' as description,+ format(+ 'Table \`%s\`.\`%s\` has excessive bloat',+ bloat_data.schemaname,+ bloat_data.object_name+ ) as detail,+ 'Consider running vacuum full (WARNING: incurs downtime) and tweaking autovacuum settings to reduce bloat.' as remediation,+ jsonb_build_object(+ 'schema', bloat_data.schemaname,+ 'name', bloat_data.object_name,+ 'type', bloat_data.type+ ) as metadata,+ format(+ 'table_bloat_%s_%s',+ bloat_data.schemaname,+ bloat_data.object_name+ ) as cache_key+from+ bloat_data+where+ bloat > 70.0+ and raw_waste > (20 * 1024 * 1024) -- filter for waste > 200 MB+order by+ schemaname,+ object_name)+union all+(+select+ 'fkey_to_auth_unique' as name,+ 'Foreign Key to Auth Unique Constraint' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects user defined foreign keys to unique constraints in the auth schema.' as description,+ format(+ 'Table \`%s\`.\`%s\` has a foreign key \`%s\` referencing an auth unique constraint',+ n.nspname, -- referencing schema+ c_rel.relname, -- referencing table+ c.conname -- fkey name+ ) as detail,+ 'Drop the foreign key constraint that references the auth schema.' as remediation,+ jsonb_build_object(+ 'schema', n.nspname,+ 'name', c_rel.relname,+ 'foreign_key', c.conname+ ) as metadata,+ format(+ 'fkey_to_auth_unique_%s_%s_%s',+ n.nspname, -- referencing schema+ c_rel.relname, -- referencing table+ c.conname+ ) as cache_key+from+ pg_catalog.pg_constraint c+ join pg_catalog.pg_class c_rel+ on c.conrelid = c_rel.oid+ join pg_catalog.pg_namespace n+ on c_rel.relnamespace = n.oid+ join pg_catalog.pg_class ref_rel+ on c.confrelid = ref_rel.oid+ join pg_catalog.pg_namespace cn+ on ref_rel.relnamespace = cn.oid+ join pg_catalog.pg_index i+ on c.conindid = i.indexrelid+where c.contype = 'f'+ and cn.nspname = 'auth'+ and i.indisunique+ and not i.indisprimary)+union all+(+select+ 'extension_versions_outdated' as name,+ 'Extension Versions Outdated' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects extensions that are not using the default (recommended) version.' as description,+ format(+ 'Extension \`%s\` is using version \`%s\` but version \`%s\` is available. Using outdated extension versions may expose the database to security vulnerabilities.',+ ext.name,+ ext.installed_version,+ ext.default_version+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0022_extension_versions_outdated' as remediation,+ jsonb_build_object(+ 'extension_name', ext.name,+ 'installed_version', ext.installed_version,+ 'default_version', ext.default_version+ ) as metadata,+ format(+ 'extension_versions_outdated_%s_%s',+ ext.name,+ ext.installed_version+ ) as cache_key+from+ pg_catalog.pg_available_extensions ext+join+ -- ignore versions not in pg_available_extension_versions+ -- e.g. residue of pg_upgrade+ pg_catalog.pg_available_extension_versions extv+ on extv.name = ext.name and extv.installed+where+ ext.installed_version is not null+ and ext.default_version is not null+ and ext.installed_version != ext.default_version+order by+ ext.name)+union all+(+-- Detects tables exposed via API that contain columns with sensitive names+-- Inspired by patterns from security scanners that detect PII/credential exposure+with sensitive_patterns as (+ select unnest(array[+ -- Authentication & Credentials+ 'password', 'passwd', 'pwd', 'passphrase',+ 'secret', 'secret_key', 'private_key', 'api_key', 'apikey',+ 'auth_key', 'token', 'jwt', 'access_token', 'refresh_token',+ 'oauth_token', 'session_token', 'bearer_token', 'auth_code',+ 'session_id', 'session_key', 'session_secret',+ 'recovery_code', 'backup_code', 'verification_code',+ 'otp', 'two_factor', '2fa_secret', '2fa_code',+ -- Personal Identifiers+ 'ssn', 'social_security', 'social_security_number',+ 'driver_license', 'drivers_license', 'license_number',+ 'passport_number', 'passport_id', 'national_id', 'tax_id',+ -- Financial Information+ 'credit_card', 'card_number', 'cvv', 'cvc', 'cvn',+ 'bank_account', 'account_number', 'routing_number',+ 'iban', 'swift_code', 'bic',+ -- Health & Medical+ 'health_record', 'medical_record', 'patient_id',+ 'insurance_number', 'health_insurance', 'medical_insurance',+ 'treatment',+ -- Device Identifiers+ 'mac_address', 'macaddr', 'imei', 'device_uuid',+ -- Digital Keys & Certificates+ 'pgp_key', 'gpg_key', 'ssh_key', 'certificate',+ 'license_key', 'activation_key',+ -- Biometric Data+ 'facial_recognition'+ ]) as pattern+),+exposed_tables as (+ select+ n.nspname as schema_name,+ c.relname as table_name,+ c.oid as table_oid+ from+ pg_catalog.pg_class c+ join pg_catalog.pg_namespace n+ on c.relnamespace = n.oid+ where+ c.relkind = 'r' -- regular tables+ and (+ pg_catalog.has_table_privilege('anon', c.oid, 'SELECT')+ or pg_catalog.has_table_privilege('authenticated', c.oid, 'SELECT')+ )+ and n.nspname = any(array(select trim(unnest(string_to_array(current_setting('pgrst.db_schemas', 't'), ',')))))+ and n.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+ -- Only flag tables without RLS enabled+ and not c.relrowsecurity+),+sensitive_columns as (+ select+ et.schema_name,+ et.table_name,+ a.attname as column_name,+ sp.pattern as matched_pattern+ from+ exposed_tables et+ join pg_catalog.pg_attribute a+ on a.attrelid = et.table_oid+ and a.attnum > 0+ and not a.attisdropped+ cross join sensitive_patterns sp+ where+ -- Match column name against sensitive patterns (case insensitive), allowing '-'/'_' variants+ replace(lower(a.attname), '-', '_') = sp.pattern+)+select+ 'sensitive_columns_exposed' as name,+ 'Sensitive Columns Exposed' as title,+ 'ERROR' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects tables exposed via API that contain columns with potentially sensitive data (PII, credentials, financial info) without RLS protection.' as description,+ format(+ 'Table \`%s.%s\` is exposed via API without RLS and contains potentially sensitive column(s): %s. This may lead to data exposure.',+ schema_name,+ table_name,+ string_agg(distinct column_name, ', ' order by column_name)+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0023_sensitive_columns_exposed' as remediation,+ jsonb_build_object(+ 'schema', schema_name,+ 'name', table_name,+ 'type', 'table',+ 'sensitive_columns', array_agg(distinct column_name order by column_name),+ 'matched_patterns', array_agg(distinct matched_pattern order by matched_pattern)+ ) as metadata,+ format(+ 'sensitive_columns_exposed_%s_%s',+ schema_name,+ table_name+ ) as cache_key+from+ sensitive_columns+group by+ schema_name,+ table_name+order by+ schema_name,+ table_name)+union all+(+-- Detects RLS policies that are overly permissive (e.g., USING (true), USING (1=1))+-- These policies effectively disable row-level security while giving a false sense of security+with policies as (+ select+ nsp.nspname as schema_name,+ pb.tablename as table_name,+ pc.relrowsecurity as is_rls_active,+ pa.polname as policy_name,+ pa.polpermissive as is_permissive,+ pa.polroles as role_oids,+ (select array_agg(r::regrole::text) from unnest(pa.polroles) as x(r)) as roles,+ case pa.polcmd+ when 'r' then 'SELECT'+ when 'a' then 'INSERT'+ when 'w' then 'UPDATE'+ when 'd' then 'DELETE'+ when '*' then 'ALL'+ end as command,+ pb.qual,+ pb.with_check,+ -- Normalize expressions by removing whitespace and lowercasing+ replace(replace(replace(lower(coalesce(pb.qual, '')), ' ', ''), E'\n', ''), E'\t', '') as normalized_qual,+ replace(replace(replace(lower(coalesce(pb.with_check, '')), ' ', ''), E'\n', ''), E'\t', '') as normalized_with_check+ from+ pg_catalog.pg_policy pa+ join pg_catalog.pg_class pc+ on pa.polrelid = pc.oid+ join pg_catalog.pg_namespace nsp+ on pc.relnamespace = nsp.oid+ join pg_catalog.pg_policies pb+ on pc.relname = pb.tablename+ and nsp.nspname = pb.schemaname+ and pa.polname = pb.policyname+ where+ pc.relkind = 'r' -- regular tables+ and nsp.nspname not in (+ '_timescaledb_cache', '_timescaledb_catalog', '_timescaledb_config', '_timescaledb_internal', 'auth', 'cron', 'extensions', 'graphql', 'graphql_public', 'information_schema', 'net', 'pgmq', 'pgroonga', 'pgsodium', 'pgsodium_masks', 'pgtle', 'pgbouncer', 'pg_catalog', 'pgtle', 'realtime', 'repack', 'storage', 'supabase_functions', 'supabase_migrations', 'tiger', 'topology', 'vault'+ )+),+permissive_patterns as (+ select+ p.*,+ -- Check for always-true USING clause patterns+ -- Note: SELECT with (true) is often intentional and documented, so we only flag UPDATE/DELETE+ case when (+ command in ('UPDATE', 'DELETE', 'ALL')+ and (+ normalized_qual in ('true', '(true)', '1=1', '(1=1)')+ -- Empty or null qual on permissive policy means allow all+ or (qual is null and is_permissive)+ )+ ) then true else false end as has_permissive_using,+ -- Check for always-true WITH CHECK clause patterns+ case when (+ normalized_with_check in ('true', '(true)', '1=1', '(1=1)')+ -- Empty with_check on INSERT means allow all (INSERT has no USING to fall back on)+ or (with_check is null and is_permissive and command = 'INSERT')+ -- Empty with_check on UPDATE/ALL with permissive USING means allow all writes+ or (with_check is null and is_permissive and command in ('UPDATE', 'ALL')+ and normalized_qual in ('true', '(true)', '1=1', '(1=1)'))+ ) then true else false end as has_permissive_with_check+ from+ policies p+ where+ -- Only check tables with RLS enabled (otherwise it's a different lint)+ is_rls_active+ -- Only check permissive policies (restrictive policies with true are less dangerous)+ and is_permissive+ -- Only flag policies that apply to anon or authenticated roles (or public/all roles)+ and (+ role_oids = array[0::oid] -- public (all roles)+ or exists (+ select 1+ from unnest(role_oids) as r+ where r::regrole::text in ('anon', 'authenticated')+ )+ )+)+select+ 'rls_policy_always_true' as name,+ 'RLS Policy Always True' as title,+ 'WARN' as level,+ 'EXTERNAL' as facing,+ array['SECURITY'] as categories,+ 'Detects RLS policies that use overly permissive expressions like \`USING (true)\` or \`WITH CHECK (true)\` for UPDATE, DELETE, or INSERT operations. SELECT policies with \`USING (true)\` are intentionally excluded as this pattern is often used deliberately for public read access.' as description,+ format(+ 'Table \`%s.%s\` has an RLS policy \`%s\` for \`%s\` that allows unrestricted access%s. This effectively bypasses row-level security for %s.',+ schema_name,+ table_name,+ policy_name,+ command,+ case+ when has_permissive_using and has_permissive_with_check then ' (both USING and WITH CHECK are always true)'+ when has_permissive_using then ' (USING clause is always true)'+ when has_permissive_with_check then ' (WITH CHECK clause is always true)'+ else ''+ end,+ array_to_string(roles, ', ')+ ) as detail,+ '${docsUrl}/guides/database/database-linter?lint=0024_permissive_rls_policy' as remediation,+ jsonb_build_object(+ 'schema', schema_name,+ 'name', table_name,+ 'type', 'table',+ 'policy_name', policy_name,+ 'command', command,+ 'roles', roles,+ 'qual', qual,+ 'with_check', with_check,+ 'permissive_using', has_permissive_using,+ 'permissive_with_check', has_permissive_with_check+ ) as metadata,+ format(+ 'rls_policy_always_true_%s_%s_%s',+ schema_name,+ table_name,+ policy_name+ ) as cache_key+from+ permissive_patterns+where+ has_permissive_using or has_permissive_with_check+order by+ schema_name,+ table_name,+ policy_name)`.trim()diff --git a/apps/studio/data/queries/sql/tables-without-rls.ts b/packages/pg-meta/src/sql/studio/database/check-tables-without-rls.tssimilarity index 92%rename from apps/studio/data/queries/sql/tables-without-rls.tsrename to packages/pg-meta/src/sql/studio/database/check-tables-without-rls.tsindex 6251d1671f6..3c0aba825db 100644--- a/apps/studio/data/queries/sql/tables-without-rls.ts+++ b/packages/pg-meta/src/sql/studio/database/check-tables-without-rls.ts@@ -1,4 +1,4 @@-import { quoteLiteral } from '@/lib/pg-format'+import { literal } from '../../../pg-format'/*** Builds a SQL query that returns entities exposed through the Data API that@@ -12,8 +12,8 @@ import { quoteLiteral } from '@/lib/pg-format'* Checks against the _target_ schemas rather than the currently active* PostgREST config, so it works correctly when enabling the Data API.*/-export const unsafeEntitiesInApiSql = (schemas: Array<string>) => {- const schemaList = schemas.map(quoteLiteral).join(', ')+export const getUnsafeEntitiesInApiSql = ({ schemas }: { schemas: Array<string> }) => {+ const schemaList = schemas.map(literal).join(', ')return /* SQL */ `selectdiff --git a/packages/pg-meta/src/sql/studio/database/fdw.ts b/packages/pg-meta/src/sql/studio/database/fdw.tsnew file mode 100644index 00000000000..102cd5cba30--- /dev/null+++ b/packages/pg-meta/src/sql/studio/database/fdw.ts@@ -0,0 +1,384 @@+type SimplifiedWrapperMeta = {+ handlerName: string+ validatorName: string+ server: { options: { name: string; encrypted: boolean }[] }+}++export const getFDWsSql = () => {+ const sql = /* SQL */ `+ select+ s.oid as "id",+ w.fdwname as "name",+ s.srvname as "server_name",+ s.srvoptions as "server_options",+ c.proname as "handler",+ (+ select jsonb_agg(+ jsonb_build_object(+ 'id', c.oid::bigint,+ 'schema', relnamespace::regnamespace::text,+ 'name', c.relname,+ 'columns', (+ select jsonb_agg(+ jsonb_build_object(+ 'name', a.attname,+ 'type', pg_catalog.format_type(a.atttypid, a.atttypmod)+ )+ )+ from pg_catalog.pg_attribute a+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped+ ),+ 'options', t.ftoptions+ )+ )+ from pg_catalog.pg_class c+ join pg_catalog.pg_foreign_table t on c.oid = t.ftrelid+ where c.oid = any (select t.ftrelid from pg_catalog.pg_foreign_table t where t.ftserver = s.oid)+ ) as "tables"+ from pg_catalog.pg_foreign_server s+ join pg_catalog.pg_foreign_data_wrapper w on s.srvfdw = w.oid+ join pg_catalog.pg_proc c on w.fdwhandler = c.oid;+ `++ return sql+}++export function getCreateFDWSql({+ wrapperMeta,+ formState,+ mode,+ tables,+ sourceSchema,+ targetSchema,+ schemaOptions = [],+}: {+ wrapperMeta: SimplifiedWrapperMeta+ formState: {+ [k: string]: string+ }+ // If mode is skip, the wrapper will skip the last step, binding the schema/tables to foreign data. This could be done later.+ mode: 'tables' | 'schema' | 'skip'+ tables: any[]+ sourceSchema: string+ targetSchema: string+ schemaOptions?: string[]+}) {+ const newSchemasSql = tables+ .filter((table) => table.is_new_schema)+ .map((table) => /* SQL */ `create schema if not exists ${table.schema_name};`)+ .join('\n')++ const createWrapperSql = /* SQL */ `+ create foreign data wrapper "${formState.wrapper_name}"+ handler "${wrapperMeta.handlerName}"+ validator "${wrapperMeta.validatorName}";+ `++ const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)+ const unencryptedOptions = wrapperMeta.server.options.filter((option) => !option.encrypted)++ const createEncryptedKeysSqlArray = encryptedOptions.map((option) => {+ const key = `${formState.wrapper_name}_${option.name}`+ // Escape single quotes in postgresql by doubling them up+ const value = (formState[option.name] || '').replace(/'/g, "''")++ return /* SQL */ `+ do $$+ begin+ -- Old wrappers has an implicit dependency on pgsodium. For new wrappers+ -- we use Vault directly.+ if (select extversion from pg_extension where extname = 'wrappers') in (+ '0.1.0',+ '0.1.1',+ '0.1.4',+ '0.1.5',+ '0.1.6',+ '0.1.7',+ '0.1.8',+ '0.1.9',+ '0.1.10',+ '0.1.11',+ '0.1.12',+ '0.1.14',+ '0.1.15',+ '0.1.16',+ '0.1.17',+ '0.1.18',+ '0.1.19',+ '0.2.0',+ '0.3.0',+ '0.3.1',+ '0.4.0',+ '0.4.1',+ '0.4.2',+ '0.4.3',+ '0.4.4',+ '0.4.5'+ ) then+ create extension if not exists pgsodium;++ perform pgsodium.create_key(+ name := '${key}'+ );++ perform vault.create_secret(+ new_secret := '${value}',+ new_name := '${key}',+ new_key_id := (select id from pgsodium.valid_key where name = '${key}')+ );+ else+ perform vault.create_secret(+ new_secret := '${value}',+ new_name := '${key}'+ );+ end if;+ end $$;+ `+ })++ const createEncryptedKeysSql = createEncryptedKeysSqlArray.join('\n')++ const encryptedOptionsSqlArray = encryptedOptions+ .filter((option) => formState[option.name])+ .map((option) => `${option.name} ''%s''`)+ const unencryptedOptionsSqlArray = unencryptedOptions+ .filter((option) => formState[option.name])+ // wrap all option names in double quotes to handle dots+ // wrap all options values in single quotes, replace single quotes with 4 single quotes to escape them in SQL past the execute format+ .map((option) => `"${option.name}" ''${formState[option.name].replace(/'/g, `''''`)}''`)+ const optionsSqlArray = [...encryptedOptionsSqlArray, ...unencryptedOptionsSqlArray].join(',')++ const createServerSql = /* SQL */ `+ do $$+ declare+ -- Old wrappers has an implicit dependency on pgsodium. For new wrappers+ -- we use Vault directly.+ is_using_old_wrappers bool;+ ${encryptedOptions.map((option) => `v_${option.name} text;`).join('\n')}+ begin+ is_using_old_wrappers := (select extversion from pg_extension where extname = 'wrappers') in (+ '0.1.0',+ '0.1.1',+ '0.1.4',+ '0.1.5',+ '0.1.6',+ '0.1.7',+ '0.1.8',+ '0.1.9',+ '0.1.10',+ '0.1.11',+ '0.1.12',+ '0.1.14',+ '0.1.15',+ '0.1.16',+ '0.1.17',+ '0.1.18',+ '0.1.19',+ '0.2.0',+ '0.3.0',+ '0.3.1',+ '0.4.0',+ '0.4.1',+ '0.4.2',+ '0.4.3',+ '0.4.4',+ '0.4.5'+ );+ ${encryptedOptions+ .map(+ (option) => /* SQL */ `+ if is_using_old_wrappers then+ select id into v_${option.name} from pgsodium.valid_key where name = '${formState.wrapper_name}_${option.name}' limit 1;+ else+ select id into v_${option.name} from vault.secrets where name = '${formState.wrapper_name}_${option.name}' limit 1;+ end if;+ `+ )+ .join('\n')}++ execute format(+ E'create server "${formState.server_name}" foreign data wrapper "${formState.wrapper_name}" options (${optionsSqlArray});',+ ${encryptedOptions+ .filter((option) => formState[option.name])+ .map((option) => `v_${option.name}`)+ .join(',\n')}+ );+ end $$;+ `++ const createTablesSql = tables+ .map((newTable) => {+ const columns = newTable.columns as {+ name: string+ type: string+ }[]++ return /* SQL */ `+ create foreign table "${newTable.schema_name}"."${newTable.table_name}" (+ ${columns.map((column) => `"${column.name}" ${column.type}`).join(',\n ')}+ )+ server ${formState.server_name}+ options (+ ${Object.entries(newTable)+ .filter(+ ([key, value]) =>+ key !== 'table_name' &&+ key !== 'schema_name' &&+ key !== 'columns' &&+ key !== 'index' &&+ key !== 'is_new_schema' &&+ Boolean(value)+ )+ .map(([key, value]) => `${key} '${value}'`)+ .join(',\n ')}+ );+ `+ })+ .join('\n\n')++ const options = [...schemaOptions, "strict 'true'"].join(', ')++ const importForeignSchemaSql = /* SQL */ `+ import foreign schema "${sourceSchema}" from server ${formState.server_name} into ${targetSchema} options (${options});+`++ const sql = /* SQL */ `+ ${newSchemasSql}++ ${createWrapperSql}++ ${createEncryptedKeysSql}++ ${createServerSql}++ ${mode === 'tables' ? createTablesSql : ''}++ ${mode === 'schema' ? importForeignSchemaSql : ''}+ `++ return sql+}++export const getDeleteFDWSql = ({+ wrapper,+ wrapperMeta,+}: {+ wrapper: { name: string }+ wrapperMeta: SimplifiedWrapperMeta+}) => {+ const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)++ const deleteEncryptedSecretsSqlArray = encryptedOptions.map((option) => {+ const key = `${wrapper.name}_${option.name}`++ return /* SQL */ `+ do $$+ begin+ -- Old wrappers has an implicit dependency on pgsodium. For new wrappers+ -- we use Vault directly.+ if (select extversion from pg_extension where extname = 'wrappers') in (+ '0.1.0',+ '0.1.1',+ '0.1.4',+ '0.1.5',+ '0.1.6',+ '0.1.7',+ '0.1.8',+ '0.1.9',+ '0.1.10',+ '0.1.11',+ '0.1.12',+ '0.1.14',+ '0.1.15',+ '0.1.16',+ '0.1.17',+ '0.1.18',+ '0.1.19',+ '0.2.0',+ '0.3.0',+ '0.3.1',+ '0.4.0',+ '0.4.1',+ '0.4.2',+ '0.4.3',+ '0.4.4',+ '0.4.5'+ ) then+ delete from vault.secrets where key_id = (select id from pgsodium.valid_key where name = '${key}');++ delete from pgsodium.key where name = '${key}';+ else+ delete from vault.secrets where name = '${key}';+ end if;+ end $$;+ `+ })++ const deleteEncryptedSecretsSql = deleteEncryptedSecretsSqlArray.join('\n')++ const sql = /* SQL */ `+ drop foreign data wrapper if exists "${wrapper.name}" cascade;++ ${deleteEncryptedSecretsSql}+ `++ return sql+}++export const getUpdateFDWSql = ({+ wrapper,+ wrapperMeta,+ formState,+ tables,+}: {+ wrapper: { name: string }+ wrapperMeta: SimplifiedWrapperMeta+ formState: { [k: string]: string }+ tables: any[]+}) => {+ const deleteWrapperSql = getDeleteFDWSql({ wrapper, wrapperMeta })+ const createWrapperSql = getCreateFDWSql({+ wrapperMeta,+ formState,+ tables,+ mode: 'tables',+ sourceSchema: '',+ targetSchema: '',+ })++ const sql = /* SQL */ `+ ${deleteWrapperSql}++ ${createWrapperSql}+ `++ return sql+}++export function getImportForeignSchemaSql({+ serverName,+ sourceSchema,+ targetSchema,+ schemaOptions = [],+}: {+ serverName: string+ sourceSchema: string+ targetSchema: string+ schemaOptions?: string[]+}) {+ const options = [...schemaOptions, "strict 'true'"].join(', ')++ const sql = /* SQL */ `+ import foreign schema "${sourceSchema}" from server ${serverName} into ${targetSchema} options (${options});+`++ return sql+}++export function getDropForeignTableSql({ schema, table }: { schema: string; table: string }) {+ const sql = /* SQL */ `+drop foreign table if exists "${schema}"."${table}";+`++ return sql+}diff --git a/packages/pg-meta/src/sql/studio/database/index.ts b/packages/pg-meta/src/sql/studio/database/index.tsindex 293e332cdff..0b582682048 100644--- a/packages/pg-meta/src/sql/studio/database/index.ts+++ b/packages/pg-meta/src/sql/studio/database/index.ts@@ -1,7 +1,9 @@export * from './check-tables-anon-authenticated-access'+export * from './check-tables-without-rls'export * from './columns'export * from './cron-jobs'export * from './extensions'+export * from './fdw'export * from './get-count-estimate'export * from './indexes'export * from './migrations'@@ -11,4 +13,6 @@ export * from './queues'export * from './rows'export * from './table-definition'export * from './triggers'+export * from './types'+export * from './vault'export * from './views'diff --git a/packages/pg-meta/src/sql/studio/database/migrations.ts b/packages/pg-meta/src/sql/studio/database/migrations.tsindex 2d0148f289d..30159cdbec3 100644--- a/packages/pg-meta/src/sql/studio/database/migrations.ts+++ b/packages/pg-meta/src/sql/studio/database/migrations.ts@@ -8,3 +8,30 @@ export const getMigrationsSql = () => {return sql}++export const getCreateMigrationsTableSQL = () => {+ return /* SQL */ `+ create schema if not exists supabase_migrations;+ create table if not exists supabase_migrations.schema_migrations (+ version text not null primary key,+ statements text[],+ name text+ );+ `.trim()+}++export const getInsertMigrationSQL = ({+ name,+ version,+ statements,+}: {+ name: string+ version: string+ statements: string+}) => {+ return /* SQL */ `+ insert into supabase_migrations.schema_migrations (version, statements, name)+ select '${version}', array_agg(jsonb_statements)::text[], '${name}'+ from jsonb_array_elements_text($statements$${statements}$statements$::jsonb) as jsonb_statements;+ `+}diff --git a/packages/pg-meta/src/sql/studio/database/types.ts b/packages/pg-meta/src/sql/studio/database/types.tsnew file mode 100644index 00000000000..b943bb1dc3d--- /dev/null+++ b/packages/pg-meta/src/sql/studio/database/types.ts@@ -0,0 +1,71 @@+import { wrapWithTransaction } from '../../../query'++export const getCreateEnumeratedTypeSQL = ({+ schema,+ name,+ values,+ description,+}: {+ schema: string+ name: string+ values: string[]+ description?: string+}) => {+ const createSql = `create type "${schema}"."${name}" as enum (${values+ .map((x) => `'${x}'`)+ .join(', ')});`+ const commentSql =+ description !== undefined ? `comment on type "${schema}"."${name}" is '${description}';` : ''+ const sql = wrapWithTransaction(`${createSql} ${commentSql}`)+ return sql+}++export const getDeleteEnumeratedTypeSQL = ({ schema, name }: { schema: string; name: string }) => {+ return `drop type if exists ${schema}."${name}"`+}++export const getUpdateEnumeratedTypeSQL = ({+ schema,+ name,+ description,+ values = [],+}: {+ schema: string+ name: { original: string; updated: string }+ description?: string+ values?: { original: string; updated: string; isNew: boolean }[]+}) => {+ const statements: string[] = []+ if (name.original !== name.updated) {+ statements.push(`alter type "${schema}"."${name.original}" rename to "${name.updated}";`)+ }+ if (values.length > 0) {+ values.forEach((x, idx) => {+ if (x.isNew) {+ if (idx === 0) {+ // Consider if any new enums were added before any existing enums+ const firstExistingEnumValue = values.find((x) => !x.isNew)+ statements.push(+ `alter type "${schema}"."${name.updated}" add value '${x.updated}' before '${firstExistingEnumValue?.original}';`+ )+ } else {+ statements.push(+ `alter type "${schema}"."${name.updated}" add value '${x.updated}' after '${+ values[idx - 1].updated+ }';`+ )+ }+ } else if (x.original !== x.updated) {+ statements.push(+ `alter type "${schema}"."${name.updated}" rename value '${x.original}' to '${x.updated}';`+ )+ }+ })+ }+ if (description !== undefined) {+ statements.push(`comment on type "${schema}"."${name.updated}" is '${description}';`)+ }++ const sql = wrapWithTransaction(statements.join(' '))+ return sql+}diff --git a/packages/pg-meta/src/sql/studio/database/vault.ts b/packages/pg-meta/src/sql/studio/database/vault.tsnew file mode 100644index 00000000000..9d1bb0aae0a--- /dev/null+++ b/packages/pg-meta/src/sql/studio/database/vault.ts@@ -0,0 +1,43 @@+import { literal } from '../../../pg-format'++export const getCreateVaultSecretSQL = ({+ secret,+ name,+ description,+}: {+ secret: string+ name?: string+ description?: string+}) => {+ const sql = /* SQL */ `+ select vault.create_secret(+ new_secret := ${literal(secret)}+ ${name ? `, new_name := ${literal(name)}` : ''}+ ${description ? `, new_description := ${literal(description)}` : ''}+ )+ `.trim()++ return sql+}++export const getUpdateVaultSecretSQL = ({+ id,+ secret,+ name,+ description,+}: {+ id: string+ secret?: string+ name?: string+ description?: string+}) => {+ const sql = /* SQL */ `+select vault.update_secret(+ secret_id := ${literal(id)}+ ${secret ? `, new_secret := ${literal(secret)}` : ''}+ ${name ? `, new_name := ${literal(name)}` : ''}+ ${description ? `, new_description := ${literal(description)}` : ''}+)+`.trim()+ return sql+}diff --git a/packages/pg-meta/src/sql/studio/role-impersonation.ts b/packages/pg-meta/src/sql/studio/role-impersonation.tsnew file mode 100644index 00000000000..101961466b5--- /dev/null+++ b/packages/pg-meta/src/sql/studio/role-impersonation.ts@@ -0,0 +1,57 @@+import { literal } from '../../pg-format'++function getPostgrestRoleImpersonationSql({+ role,+ unexpiredClaims,+}: {+ role: string+ unexpiredClaims: Object+}) {+ return `+select set_config('role', ${literal(role)}, true),+set_config('request.jwt.claims', ${literal(JSON.stringify(unexpiredClaims))}, true),+set_config('request.method', 'POST', true),+set_config('request.path', '/impersonation-example-request-path', true),+set_config('request.headers', '{"accept": "*/*"}', true);+ `.trim()+}++function getCustomRoleImpersonationSql(roleName: string) {+ return /* SQL */ `+ set local role ${literal(roleName)};+ `.trim()+}++// Includes getPostgrestRoleImpersonationSql() and wrapWithRoleImpersonation()+export const ROLE_IMPERSONATION_SQL_LINE_COUNT = 11+export const ROLE_IMPERSONATION_NO_RESULTS = 'ROLE_IMPERSONATION_NO_RESULTS'++export const getImpersonationSQL = ({+ role,+ unexpiredClaims,+ sql,+}: {+ role: {+ type: 'postgrest' | 'custom'+ role: string+ }+ unexpiredClaims?: Object+ sql: string+}) => {+ const impersonationSql =+ role.type === 'postgrest'+ ? unexpiredClaims !== undefined+ ? getPostgrestRoleImpersonationSql({ role: role.role, unexpiredClaims })+ : ''+ : getCustomRoleImpersonationSql(role.role)++ return /* SQL */ `+ ${impersonationSql}++ -- If the users sql returns no rows, pg-meta will+ -- fallback to returning the result of the impersonation sql.+ select 1 as "${ROLE_IMPERSONATION_NO_RESULTS}";++ ${sql}+ `.trim()+}diff --git a/packages/pg-meta/src/sql/studio/storage/delete-bucket-prefix.ts b/packages/pg-meta/src/sql/studio/storage/delete-bucket-prefix.tsnew file mode 100644index 00000000000..bdb35b1331a--- /dev/null+++ b/packages/pg-meta/src/sql/studio/storage/delete-bucket-prefix.ts@@ -0,0 +1,12 @@+export const getDeleteBucketPrefixSQL = ({+ bucketId,+ prefix,+}: {+ bucketId: string+ prefix: string+}) => {+ const sql = /* SQL */ `+select storage.delete_prefix('${bucketId}', '${prefix}');+`.trim()+ return sql+}diff --git a/packages/pg-meta/src/sql/studio/storage/index.ts b/packages/pg-meta/src/sql/studio/storage/index.tsindex 3b6feef9a28..cbccc9a0d2b 100644--- a/packages/pg-meta/src/sql/studio/storage/index.ts+++ b/packages/pg-meta/src/sql/studio/storage/index.ts@@ -1 +1,2 @@export * from './get-largest-size-limit-buckets'+export * from './delete-bucket-prefix'diff --git a/packages/pg-meta/src/sql/studio/table-editor/table.ts b/packages/pg-meta/src/sql/studio/table-editor/table.tsindex 87f4240f681..19cb3b30aad 100644--- a/packages/pg-meta/src/sql/studio/table-editor/table.ts+++ b/packages/pg-meta/src/sql/studio/table-editor/table.ts@@ -30,3 +30,313 @@ export const getDuplicateRowsSQL = ({}) => {return `INSERT INTO ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} SELECT * FROM ${ident(sourceTableSchema)}.${ident(sourceTableName)};`}++export const getTableEditorSql = ({ id }: { id?: number }) => {+ if (!id) return ''++ return /* SQL */ `+ with base_table_info as (+ select+ c.oid::int8 as id,+ nc.nspname as schema,+ c.relname as name,+ c.relkind,+ c.relrowsecurity as rls_enabled,+ c.relforcerowsecurity as rls_forced,+ c.relreplident,+ c.relowner,+ obj_description(c.oid) as comment,+ fs.srvname as foreign_server_name,+ fdw.fdwname as foreign_data_wrapper_name,+ fdw_handler.proname as foreign_data_wrapper_handler+ from pg_class c+ join pg_namespace nc on nc.oid = c.relnamespace+ left join pg_foreign_table ft on ft.ftrelid = c.oid+ left join pg_foreign_server fs on fs.oid = ft.ftserver+ left join pg_foreign_data_wrapper fdw on fdw.oid = fs.srvfdw+ left join pg_proc fdw_handler on fdw.fdwhandler = fdw_handler.oid+ where c.oid = ${id}+ and not pg_is_other_temp_schema(nc.oid)+ and (+ pg_has_role(c.relowner, 'USAGE')+ or has_table_privilege(+ c.oid,+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'+ )+ or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')+ )+ ),+ table_stats as (+ select+ b.id,+ case+ when b.relreplident = 'd' then 'DEFAULT'+ when b.relreplident = 'i' then 'INDEX'+ when b.relreplident = 'f' then 'FULL'+ else 'NOTHING'+ end as replica_identity,+ pg_total_relation_size(format('%I.%I', b.schema, b.name))::int8 as bytes,+ pg_size_pretty(pg_total_relation_size(format('%I.%I', b.schema, b.name))) as size,+ pg_stat_get_live_tuples(b.id) as live_rows_estimate,+ pg_stat_get_dead_tuples(b.id) as dead_rows_estimate+ from base_table_info b+ where b.relkind in ('r', 'p')+ ),+ primary_keys as (+ select+ i.indrelid as table_id,+ jsonb_agg(+ jsonb_build_object(+ 'schema', n.nspname,+ 'table_name', c.relname,+ 'table_id', i.indrelid::int8,+ 'name', a.attname+ )+ order by array_position(i.indkey, a.attnum)+ ) as primary_keys+ from pg_index i+ join pg_class c on i.indrelid = c.oid+ join pg_namespace n on c.relnamespace = n.oid+ join pg_attribute a on a.attrelid = c.oid and a.attnum = any(i.indkey)+ where i.indisprimary+ group by i.indrelid+ ),+ index_cols as (+ select+ i.indrelid as table_id,+ i.indkey,+ array_agg(+ a.attname+ order by array_position(i.indkey, a.attnum)+ ) as columns+ from pg_index i+ join pg_class c on i.indrelid = c.oid+ join pg_attribute a on a.attrelid = c.oid+ and a.attnum = any(i.indkey)+ where i.indisunique+ and i.indisprimary = false+ group by i.indrelid, i.indkey+ ),+ unique_indexes as (+ select+ ic.table_id,+ jsonb_agg(+ jsonb_build_object(+ 'schema', n.nspname,+ 'table_name', c.relname,+ 'table_id', ic.table_id::int8,+ 'columns', ic.columns+ )+ ) as unique_indexes+ from index_cols ic+ join pg_class c on c.oid = ic.table_id+ join pg_namespace n on n.oid = c.relnamespace+ group by ic.table_id+ ),+ relationships as (+ select+ c.conrelid as source_id,+ c.confrelid as target_id,+ jsonb_build_object(+ 'id', c.oid::int8,+ 'constraint_name', c.conname,+ 'deletion_action', c.confdeltype,+ 'update_action', c.confupdtype,+ 'source_schema', nsa.nspname,+ 'source_table_name', csa.relname,+ 'source_column_name', sa.attname,+ 'target_table_schema', nta.nspname,+ 'target_table_name', cta.relname,+ 'target_column_name', ta.attname+ ) as rel_info+ from pg_constraint c+ join pg_class csa on c.conrelid = csa.oid+ join pg_namespace nsa on csa.relnamespace = nsa.oid+ join pg_attribute sa on (sa.attrelid = c.conrelid and sa.attnum = any(c.conkey))+ join pg_class cta on c.confrelid = cta.oid+ join pg_namespace nta on cta.relnamespace = nta.oid+ join pg_attribute ta on (ta.attrelid = c.confrelid and ta.attnum = any(c.confkey))+ where c.contype = 'f'+ ),+ columns as (+ select+ a.attrelid as table_id,+ jsonb_agg(jsonb_build_object(+ 'id', (a.attrelid || '.' || a.attnum),+ 'table_id', c.oid::int8,+ 'schema', nc.nspname,+ 'table', c.relname,+ 'ordinal_position', a.attnum,+ 'name', a.attname,+ 'default_value', case+ when a.atthasdef then pg_get_expr(ad.adbin, ad.adrelid)+ else null+ end,+ 'data_type', case+ when t.typtype = 'd' then+ case+ when bt.typelem <> 0::oid and bt.typlen = -1 then 'ARRAY'+ when nbt.nspname = 'pg_catalog' then format_type(t.typbasetype, null)+ else 'USER-DEFINED'+ end+ else+ case+ when t.typelem <> 0::oid and t.typlen = -1 then 'ARRAY'+ when nt.nspname = 'pg_catalog' then format_type(a.atttypid, null)+ else 'USER-DEFINED'+ end+ end,+ 'format', case+ when t.typtype = 'e' then+ case+ when nt.nspname <> 'public' then concat(nt.nspname, '.', coalesce(bt.typname, t.typname))+ else coalesce(bt.typname, t.typname)+ end+ else+ coalesce(bt.typname, t.typname)+ end,+ 'is_identity', a.attidentity in ('a', 'd'),+ 'identity_generation', case a.attidentity+ when 'a' then 'ALWAYS'+ when 'd' then 'BY DEFAULT'+ else null+ end,+ 'is_generated', a.attgenerated in ('s'),+ 'is_nullable', not (a.attnotnull or t.typtype = 'd' and t.typnotnull),+ 'is_updatable', (+ b.relkind in ('r', 'p') or+ (b.relkind in ('v', 'f') and pg_column_is_updatable(b.id, a.attnum, false))+ ),+ 'is_unique', uniques.table_id is not null,+ 'check', check_constraints.definition,+ 'comment', col_description(c.oid, a.attnum),+ 'enums', coalesce(+ (+ select jsonb_agg(e.enumlabel order by e.enumsortorder)+ from pg_catalog.pg_enum e+ where e.enumtypid = coalesce(bt.oid, t.oid)+ or e.enumtypid = coalesce(bt.typelem, t.typelem)+ ),+ '[]'::jsonb+ )+ ) order by a.attnum) as columns+ from pg_attribute a+ join base_table_info b on a.attrelid = b.id+ join pg_class c on a.attrelid = c.oid+ join pg_namespace nc on c.relnamespace = nc.oid+ left join pg_attrdef ad on (a.attrelid = ad.adrelid and a.attnum = ad.adnum)+ join pg_type t on a.atttypid = t.oid+ join pg_namespace nt on t.typnamespace = nt.oid+ left join pg_type bt on (t.typtype = 'd' and t.typbasetype = bt.oid)+ left join pg_namespace nbt on bt.typnamespace = nbt.oid+ left join (+ select+ conrelid as table_id,+ conkey[1] as ordinal_position+ from pg_catalog.pg_constraint+ where contype = 'u' and cardinality(conkey) = 1+ group by conrelid, conkey[1]+ ) as uniques on uniques.table_id = a.attrelid and uniques.ordinal_position = a.attnum+ left join (+ select distinct on (conrelid, conkey[1])+ conrelid as table_id,+ conkey[1] as ordinal_position,+ substring(+ pg_get_constraintdef(oid, true),+ 8,+ length(pg_get_constraintdef(oid, true)) - 8+ ) as definition+ from pg_constraint+ where contype = 'c' and cardinality(conkey) = 1+ order by conrelid, conkey[1], oid asc+ ) as check_constraints on check_constraints.table_id = a.attrelid+ and check_constraints.ordinal_position = a.attnum+ where a.attnum > 0+ and not a.attisdropped+ group by a.attrelid+ )+ select+ case b.relkind+ when 'r' then jsonb_build_object(+ 'entity_type', b.relkind,+ 'id', b.id,+ 'schema', b.schema,+ 'name', b.name,+ 'rls_enabled', b.rls_enabled,+ 'rls_forced', b.rls_forced,+ 'replica_identity', ts.replica_identity,+ 'bytes', ts.bytes,+ 'size', ts.size,+ 'live_rows_estimate', ts.live_rows_estimate,+ 'dead_rows_estimate', ts.dead_rows_estimate,+ 'comment', b.comment,+ 'primary_keys', coalesce(pk.primary_keys, '[]'::jsonb),+ 'unique_indexes', coalesce(ui.unique_indexes, '[]'::jsonb),+ 'relationships', coalesce(+ (select jsonb_agg(r.rel_info)+ from relationships r+ where r.source_id = b.id or r.target_id = b.id),+ '[]'::jsonb+ ),+ 'columns', coalesce(c.columns, '[]'::jsonb)+ )+ when 'p' then jsonb_build_object(+ 'entity_type', b.relkind,+ 'id', b.id,+ 'schema', b.schema,+ 'name', b.name,+ 'rls_enabled', b.rls_enabled,+ 'rls_forced', b.rls_forced,+ 'replica_identity', ts.replica_identity,+ 'bytes', ts.bytes,+ 'size', ts.size,+ 'live_rows_estimate', ts.live_rows_estimate,+ 'dead_rows_estimate', ts.dead_rows_estimate,+ 'comment', b.comment,+ 'primary_keys', coalesce(pk.primary_keys, '[]'::jsonb),+ 'unique_indexes', coalesce(ui.unique_indexes, '[]'::jsonb),+ 'relationships', coalesce(+ (select jsonb_agg(r.rel_info)+ from relationships r+ where r.source_id = b.id or r.target_id = b.id),+ '[]'::jsonb+ ),+ 'columns', coalesce(c.columns, '[]'::jsonb)+ )+ when 'v' then jsonb_build_object(+ 'entity_type', b.relkind,+ 'id', b.id,+ 'schema', b.schema,+ 'name', b.name,+ 'is_updatable', (pg_relation_is_updatable(b.id, false) & 20) = 20,+ 'comment', b.comment,+ 'columns', coalesce(c.columns, '[]'::jsonb)+ )+ when 'm' then jsonb_build_object(+ 'entity_type', b.relkind,+ 'id', b.id,+ 'schema', b.schema,+ 'name', b.name,+ 'is_populated', true,+ 'comment', b.comment,+ 'columns', coalesce(c.columns, '[]'::jsonb)+ )+ when 'f' then jsonb_build_object(+ 'entity_type', b.relkind,+ 'id', b.id,+ 'schema', b.schema,+ 'name', b.name,+ 'comment', b.comment,+ 'foreign_server_name', b.foreign_server_name,+ 'foreign_data_wrapper_name', b.foreign_data_wrapper_name,+ 'foreign_data_wrapper_handler', b.foreign_data_wrapper_handler,+ 'columns', coalesce(c.columns, '[]'::jsonb)+ )+ end as entity+ from base_table_info b+ left join table_stats ts on b.id = ts.id+ left join primary_keys pk on b.id = pk.table_id+ left join unique_indexes ui on b.id = ui.table_id+ left join columns c on b.id = c.table_id;+ `.trim()+}diff --git a/apps/studio/tests/unit/lints/enrichLintsQuery.test.ts b/packages/pg-meta/test/sql/studio/lints.test.tssimilarity index 89%rename from apps/studio/tests/unit/lints/enrichLintsQuery.test.tsrename to packages/pg-meta/test/sql/studio/lints.test.tsindex 09558c2154a..39a2dbf6625 100644--- a/apps/studio/tests/unit/lints/enrichLintsQuery.test.ts+++ b/packages/pg-meta/test/sql/studio/lints.test.ts@@ -1,5 +1,6 @@-import { describe, it, expect } from 'vitest'-import { enrichLintsQuery } from 'lib/api/self-hosted/lints'+import { describe, expect, it } from 'vitest'++import { enrichLintsQuery } from '../../../src'describe('enrichLintsQuery', () => {const dummyQuery = 'SELECT 1'