The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: remove pgMetaScopedIntrospection feature flag (#52019)
Andrew Valleteaue42f4ec61233
diff --git a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsxindex 64895bcc61f..e534e674558 100644--- a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx+++ b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx@@ -2,7 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'import { keyword } from '@supabase/pg-meta'import type { PGTrigger, PGTriggerCreate } from '@supabase/pg-meta'import { useQueryClient } from '@tanstack/react-query'-import { useFlag, useParams } from 'common'+import { useParams } from 'common'import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'import { useEffect, useRef, useState } from 'react'import { SubmitHandler, useForm } from 'react-hook-form'@@ -15,10 +15,7 @@ import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialoimport { useDatabaseTriggerCreateMutation } from '@/data/database-triggers/database-trigger-create-mutation'import { useDatabaseTriggerUpdateMutation } from '@/data/database-triggers/database-trigger-update-transaction-mutation'import { useDatabaseHooksQuery } from '@/data/database-triggers/database-triggers-query'-import {- PG_META_SCOPED_INTROSPECTION_FLAG,- tableEditorQueryOptions,-} from '@/data/table-editor/table-editor-query'+import { tableEditorQueryOptions } from '@/data/table-editor/table-editor-query'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'import { isEdgeFunctionUrl } from '@/lib/api/edgeFunctions'@@ -72,7 +69,6 @@ export const EditHookPanel = () => {const { ref } = useParams()const { data: project } = useSelectedProjectQuery()const [isLoadingTable, setIsLoadingTable] = useState(false)- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)const { data: hooks = [], isSuccess } = useDatabaseHooksQuery({projectRef: project?.ref,@@ -196,7 +192,6 @@ export const EditHookPanel = () => {id: Number(values.table_id),projectRef: project?.ref,connectionString: project?.connectionString,- scoped,}))if (!selectedTable) {diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsxindex a1f101cba96..7673de8f0dc 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx@@ -1,7 +1,7 @@import * as Sentry from '@sentry/nextjs'import type { PGTable } from '@supabase/pg-meta'import { useQueryClient } from '@tanstack/react-query'-import { useFlag, useParams } from 'common'+import { useParams } from 'common'import { isEmpty, isUndefined, noop } from 'lodash'import { useState } from 'react'import { toast } from 'sonner'@@ -47,7 +47,6 @@ import type { ForeignKeyConstraint } from '@/data/database/foreign-key-constrainimport { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'import { privilegeKeys } from '@/data/privileges/keys'import { useTableApiAccessPrivilegesMutation } from '@/data/privileges/table-api-access-mutation'-import { PG_META_SCOPED_INTROSPECTION_FLAG } from '@/data/table-editor/table-editor-query'import { isTableLike, type Entity } from '@/data/table-editor/table-editor-types'import { tableRowKeys } from '@/data/table-rows/keys'import { tableKeys } from '@/data/tables/keys'@@ -193,7 +192,6 @@ export const SidePanelEditor = ({const isQueueOperationsEnabled = useIsQueueOperationsEnabled()const { updateRow, addRow, isEditPending } = useTableRowOperations()const getImpersonatedRoleState = useGetImpersonatedRoleState()- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)const [isEdited, setIsEdited] = useState<boolean>(false)const csvImportKey = useVisibleKey(snap.sidePanel?.type === 'csv-import')@@ -662,7 +660,6 @@ export const SidePanelEditor = ({isRLSEnabled,importContent,track,- scoped,})createTableSpan.setAttribute('table.created', 1)@@ -766,7 +763,6 @@ export const SidePanelEditor = ({existingForeignKeyRelations,primaryKey,track,- scoped,})if (table === undefined) {diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsxindex c8dbb0c617e..1f456d34acd 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx@@ -440,7 +440,6 @@ export const createTable = async ({isRLSEnabled,importContent,track,- scoped,}: {projectRef: stringconnectionString?: string | null@@ -455,7 +454,6 @@ export const createTable = async ({isRLSEnabled: booleanimportContent?: ImportContenttrack: Track- scoped?: boolean}) => {const queryClient = getQueryClient()@@ -674,7 +672,6 @@ export const createTable = async ({projectRef,connectionString,id: table.id,- scoped,})})@@ -695,7 +692,6 @@ export const updateTable = async ({existingForeignKeyRelations,primaryKey,track,- scoped,}: {projectRef: stringconnectionString?: string | null@@ -707,7 +703,6 @@ export const updateTable = async ({existingForeignKeyRelations: ForeignKeyConstraint[]primaryKey?: Constrainttrack: Track- scoped?: boolean}) => {const queryClient = getQueryClient()@@ -873,7 +868,6 @@ export const updateTable = async ({projectRef,connectionString,id: table.id,- scoped,}),hasError,}diff --git a/apps/studio/components/layouts/DefaultLayout.tsx b/apps/studio/components/layouts/DefaultLayout.tsxindex defd49f45a8..1762d3215dc 100644--- a/apps/studio/components/layouts/DefaultLayout.tsx+++ b/apps/studio/components/layouts/DefaultLayout.tsx@@ -18,7 +18,6 @@ import { ProjectContextProvider } from './ProjectLayout/ProjectContext'import { AppBannerWrapper } from '@/components/interfaces/App/AppBannerWrapper'import { GitHubConfigDriftBanner } from '@/components/interfaces/App/GitHubConfigDriftBanner'import { Sidebar } from '@/components/interfaces/Sidebar'-import { useSyncScopedIntrospection } from '@/data/scoped-introspection'import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'import { useCheckLatestDeploy } from '@/hooks/use-check-latest-deploy'import { IS_PLATFORM } from '@/lib/constants'@@ -45,7 +44,6 @@ export const DefaultLayout = ({headerTitle,hideMobileMenu,}: PropsWithChildren<DefaultLayoutProps>) => {- useSyncScopedIntrospection()useCheckLatestDeploy()const { ref } = useParams()diff --git a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsxindex 5a1b5c05e10..8d8171faa58 100644--- a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx+++ b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx@@ -1,4 +1,4 @@-import { useFlag, useParams } from 'common'+import { useParams } from 'common'import {CopyIcon,DownloadIcon,@@ -46,7 +46,6 @@ import type {TableApiAccessData,TableApiAccessMap,} from '@/data/privileges/table-api-access-query'-import { PG_META_SCOPED_INTROSPECTION_FLAG } from '@/data/table-editor/table-editor-query'import { useTableRowsCountQuery } from '@/data/table-rows/table-rows-count-query'import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'@@ -87,7 +86,6 @@ export const EntityListItem = ({const { data: project } = useSelectedProjectQuery()const snap = useTableEditorStateSnapshot()const { selectedSchema } = useQuerySchemaState()- const scoped = !!useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)const tabId = createTabId(entity.type, { id: entity.id })const tabs = useTabsStateSnapshot()@@ -286,7 +284,6 @@ export const EntityListItem = ({id: entity.id,projectRef: project?.ref,connectionString: project?.connectionString,- scoped,}).then((tableDefinition) => {if (!tableDefinition) {throw new Error('Failed to get table schema')diff --git a/apps/studio/data/database/table-definition-query.ts b/apps/studio/data/database/table-definition-query.tsindex 35ec50537a5..f26a82268ce 100644--- a/apps/studio/data/database/table-definition-query.ts+++ b/apps/studio/data/database/table-definition-query.ts@@ -1,15 +1,12 @@import { getTableDefinitionSql } from '@supabase/pg-meta'import { useQuery } from '@tanstack/react-query'-import { useFlag } from 'common'import { databaseKeys } from './keys'import { executeSql } from '@/data/sql/execute-sql-mutation'-import { PG_META_SCOPED_INTROSPECTION_FLAG } from '@/data/table-editor/table-editor-query'import { ResponseError, UseCustomQueryOptions } from '@/types'type GetTableDefinitionArgs = {id?: number- scoped?: boolean}export type TableDefinitionVariables = GetTableDefinitionArgs & {@@ -18,12 +15,12 @@ export type TableDefinitionVariables = GetTableDefinitionArgs & {}export async function getTableDefinition(- { projectRef, connectionString, id, scoped }: TableDefinitionVariables,+ { projectRef, connectionString, id }: TableDefinitionVariables,signal?: AbortSignal) {if (!id) throw new Error('id is required')- const sql = getTableDefinitionSql({ id, scoped })+ const sql = getTableDefinitionSql({ id })const { result } = await executeSql({projectRef,@@ -47,12 +44,9 @@ export const useTableDefinitionQuery = <TData = TableDefinitionData>(...options}: UseCustomQueryOptions<TableDefinitionData, TableDefinitionError, TData> = {}) => {- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)-return useQuery<TableDefinitionData, TableDefinitionError, TData>({- queryKey: [...databaseKeys.tableDefinition(projectRef, id), { scoped }],- queryFn: ({ signal }) =>- getTableDefinition({ projectRef, connectionString, id, scoped }, signal),+ queryKey: databaseKeys.tableDefinition(projectRef, id),+ queryFn: ({ signal }) => getTableDefinition({ projectRef, connectionString, id }, signal),enabled:enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id),...options,diff --git a/apps/studio/data/enumerated-types/enumerated-types-query.ts b/apps/studio/data/enumerated-types/enumerated-types-query.tsindex 71d2b43e968..b494ac83e3f 100644--- a/apps/studio/data/enumerated-types/enumerated-types-query.ts+++ b/apps/studio/data/enumerated-types/enumerated-types-query.ts@@ -4,7 +4,6 @@ import { useQuery } from '@tanstack/react-query'import { executeSql } from '../sql/execute-sql-mutation'import { enumeratedTypesKeys } from './keys'import type { components } from '@/data/api'-import { isScopedIntrospection, scopedIntrospectionReady } from '@/data/scoped-introspection'import type { ResponseError, UseCustomQueryOptions } from '@/types'export type EnumeratedTypesVariables = {@@ -21,9 +20,7 @@ export async function getEnumeratedTypes() {if (!projectRef) throw new Error('projectRef is required')- // Cold-load race guard -- see the module comment on scoped-introspection.ts.- await scopedIntrospectionReady()- const { sql } = pgMeta.types.list({ includedSchemas: schemas, scoped: isScopedIntrospection() })+ const { sql } = pgMeta.types.list({ includedSchemas: schemas })const { result } = await executeSql({projectRef,diff --git a/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx b/apps/studio/data/prefetchers/project.$ref.editor.$id.tsxindex 2f5ea108a11..293a1c7ea79 100644--- a/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx+++ b/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx@@ -1,5 +1,4 @@import { QueryClient, useQueryClient } from '@tanstack/react-query'-import { useFlag } from 'common'import { useRouter } from 'next/router'import { PropsWithChildren, useCallback } from 'react'@@ -11,10 +10,7 @@ import {} from '@/components/grid/SupabaseGrid.utils'import { Filter, Sort } from '@/components/grid/types'import { useConnectionStringForReadOps } from '@/data/read-replicas/replicas-query'-import {- PG_META_SCOPED_INTROSPECTION_FLAG,- prefetchTableEditor,-} from '@/data/table-editor/table-editor-query'+import { prefetchTableEditor } from '@/data/table-editor/table-editor-query'import { prefetchTableRows } from '@/data/table-rows/table-rows-query'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { RoleImpersonationState } from '@/lib/role-impersonation'@@ -30,7 +26,6 @@ interface PrefetchEditorTablePageArgs {sorts?: Sort[]filters?: Filter[]roleImpersonationState?: RoleImpersonationState- scoped?: boolean}export function prefetchEditorTablePage({@@ -42,13 +37,11 @@ export function prefetchEditorTablePage({sorts,filters,roleImpersonationState,- scoped,}: PrefetchEditorTablePageArgs) {return prefetchTableEditor(queryClient, {projectRef,connectionString,id,- scoped,}).then((entity) => {if (entity) {const { sorts: localSorts = [], filters: localFilters = [] } =@@ -65,7 +58,6 @@ export function prefetchEditorTablePage({page: 1,limit: TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE,roleImpersonationState,- scoped,})}})@@ -77,7 +69,6 @@ export function usePrefetchEditorTablePage() {const { data: project } = useSelectedProjectQuery()const { connectionString, identifier: readReplicaIdentifier } = useConnectionStringForReadOps()const roleImpersonationState = useRoleImpersonationStateSnapshot()- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)return useCallback(({ id: _id, filters, sorts }: { id?: string; filters?: Filter[]; sorts?: Sort[] }) => {@@ -97,20 +88,11 @@ export function usePrefetchEditorTablePage() {sorts,filters,roleImpersonationState: roleImpersonationState as RoleImpersonationState,- scoped,}).catch(() => {// eat prefetching errors as they are not critical})},- [- connectionString,- readReplicaIdentifier,- project,- queryClient,- roleImpersonationState,- router,- scoped,- ]+ [connectionString, readReplicaIdentifier, project, queryClient, roleImpersonationState, router])}diff --git a/apps/studio/data/privileges/column-privileges-query.ts b/apps/studio/data/privileges/column-privileges-query.tsindex 716cf8a0ad8..e5ddcad2ab3 100644--- a/apps/studio/data/privileges/column-privileges-query.ts+++ b/apps/studio/data/privileges/column-privileges-query.ts@@ -5,7 +5,6 @@ import { z } from 'zod'import { executeSql } from '../sql/execute-sql-mutation'import { privilegeKeys } from './keys'import type { components } from '@/data/api'-import { isScopedIntrospection, scopedIntrospectionReady } from '@/data/scoped-introspection'import type { ResponseError, UseCustomQueryOptions } from '@/types'export type ColumnPrivilegesVariables = {@@ -36,12 +35,9 @@ export async function getColumnPrivileges() {if (!projectRef) throw new Error('projectRef is required')- // Cold-load race guard -- see the module comment on scoped-introspection.ts.- await scopedIntrospectionReady()const sql = pgMeta.columnPrivileges.list({includedSchemas: [schema],relationName: table,- scoped: isScopedIntrospection(),}).sqlconst queryKey = ['column-privileges', schema, table]const { result } = await executeSql({ projectRef, connectionString, sql, queryKey }, signal)diff --git a/apps/studio/data/privileges/table-privileges-query.ts b/apps/studio/data/privileges/table-privileges-query.tsindex a09611363b2..e5114017ba1 100644--- a/apps/studio/data/privileges/table-privileges-query.ts+++ b/apps/studio/data/privileges/table-privileges-query.ts@@ -3,7 +3,6 @@ import { QueryClient, useQuery } from '@tanstack/react-query'import { z } from 'zod'import { privilegeKeys } from './keys'-import { isScopedIntrospection, scopedIntrospectionReady } from '@/data/scoped-introspection'import { executeSql } from '@/data/sql/execute-sql-mutation'import { ResponseError, UseCustomQueryOptions } from '@/types'@@ -23,11 +22,8 @@ async function getTablePrivileges({ projectRef, connectionString, includedSchemas }: TablePrivilegesVariables,signal?: AbortSignal) {- // Cold-load race guard -- see the module comment on scoped-introspection.ts.- await scopedIntrospectionReady()const sql = pgMeta.tablePrivileges.list({includedSchemas,- scoped: isScopedIntrospection(),}).sqlconst queryKey = ['table-privileges', includedSchemas?.join(',')]diff --git a/apps/studio/data/scoped-introspection.test.tsx b/apps/studio/data/scoped-introspection.test.tsxdeleted file mode 100644index 89081efeb52..00000000000--- a/apps/studio/data/scoped-introspection.test.tsx+++ /dev/null@@ -1,112 +0,0 @@-import { renderHook } from '@testing-library/react'-import { FeatureFlagContext } from 'common'-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'--import { PG_META_SCOPED_INTROSPECTION_FLAG } from '@/data/table-editor/table-editor-query'--const { mockIsPlatform } = vi.hoisted(() => ({ mockIsPlatform: { value: true } }))--vi.mock('@/lib/constants', async () => {- const actual = await vi.importActual<Record<string, unknown>>('@/lib/constants')- return {- ...actual,- get IS_PLATFORM() {- return mockIsPlatform.value- },- }-})--// Mirrors the real provider: `configcat` and `hasLoaded` flip together once-// `processFlags()` resolves -- an empty store (the pre-load default) is what-// makes `useFlag` read `false` before that.-function flagProvider(hasLoaded: boolean, flagValue = true) {- const configcat: Record<string, boolean> = hasLoaded- ? { [PG_META_SCOPED_INTROSPECTION_FLAG]: flagValue }- : {}- return function FlagProviderWrapper({ children }: { children: React.ReactNode }) {- return (- <FeatureFlagContext.Provider value={{ configcat, posthog: {}, hasLoaded }}>- {children}- </FeatureFlagContext.Provider>- )- }-}--describe('scoped-introspection', () => {- // Module-level singleton state -- start every test from a fresh module- // instance so the ready-promise isn't already settled from a prior test.- let mod: typeof import('./scoped-introspection')-- beforeEach(async () => {- mockIsPlatform.value = true- vi.resetModules()- mod = await import('./scoped-introspection')- })-- afterEach(() => {- vi.useRealTimers()- })-- test('isScopedIntrospection defaults to false', () => {- expect(mod.isScopedIntrospection()).toBe(false)- })-- test('setScopedIntrospection updates the accessor', () => {- mod.setScopedIntrospection(true)- expect(mod.isScopedIntrospection()).toBe(true)- })-- test('scopedIntrospectionReady stays pending until a loaded flag store hydrates it', async () => {- let settled = false- mod.scopedIntrospectionReady().then(() => {- settled = true- })-- const { unmount } = renderHook(() => mod.useSyncScopedIntrospection(), {- wrapper: flagProvider(false),- })- await Promise.resolve()- expect(settled).toBe(false)- expect(mod.isScopedIntrospection()).toBe(false) // useFlag reads false pre-load- unmount()-- renderHook(() => mod.useSyncScopedIntrospection(), { wrapper: flagProvider(true, true) })- await Promise.resolve()-- expect(settled).toBe(true)- expect(mod.isScopedIntrospection()).toBe(true)- })-- test('resolves immediately when self-hosted (flags disabled)', async () => {- mockIsPlatform.value = false-- let settled = false- mod.scopedIntrospectionReady().then(() => {- settled = true- })-- renderHook(() => mod.useSyncScopedIntrospection(), { wrapper: flagProvider(false, false) })- await Promise.resolve()-- expect(settled).toBe(true)- })-- test('falls back to resolving 5s after the first scopedIntrospectionReady() call if hydration never happens', async () => {- vi.useFakeTimers()-- let settled = false- mod.scopedIntrospectionReady().then(() => {- settled = true- })-- vi.advanceTimersByTime(4_999)- await Promise.resolve()- expect(settled).toBe(false)-- vi.advanceTimersByTime(1)- await Promise.resolve()- expect(settled).toBe(true)- // Hydration never ran -- accessor stays at its default.- expect(mod.isScopedIntrospection()).toBe(false)- })-})diff --git a/apps/studio/data/scoped-introspection.ts b/apps/studio/data/scoped-introspection.tsdeleted file mode 100644index d1b69e518b1..00000000000--- a/apps/studio/data/scoped-introspection.ts+++ /dev/null@@ -1,72 +0,0 @@-import { useFeatureFlags, useFlag } from 'common'-import { useEffect } from 'react'--import { PG_META_SCOPED_INTROSPECTION_FLAG } from '@/data/table-editor/table-editor-query'-import { IS_PLATFORM } from '@/lib/constants'--/**- * Imperative accessor for the `pgMetaScopedIntrospection` flag, read by query- * fns that opt into scoped pg-meta SQL without threading `scoped` through- * their React Query key (accepted tradeoff: a mid-session flag flip can serve- * stale-keyed cached data until the query's next natural refetch). Hydrated- * by `useSyncScopedIntrospection`, called from `DefaultLayout` -- the first- * component both of Studio's root trees (pages/_app.tsx, routes/__root.tsx)- * render inside `FeatureFlagProviderWithOrgContext`.- */-let scopedIntrospection = false--export const setScopedIntrospection = (value: boolean) => {- scopedIntrospection = value-}--export const isScopedIntrospection = () => scopedIntrospection--const READY_TIMEOUT_MS = 5_000--let isReadySettled = false-let isTimeoutArmed = false-let resolveReady: () => void = () => {}-const readyPromise = new Promise<void>((resolve) => {- resolveReady = resolve-})--const markScopedIntrospectionReady = () => {- if (isReadySettled) return- isReadySettled = true- resolveReady()-}--/**- * Resolves once `useSyncScopedIntrospection` has hydrated the accessor from a- * loaded flag store (or immediately if self-hosted) -- never before, by- * construction (see that hook). Arms a 5s fallback timer on its *first call*- * rather than at module load, so a query firing long after boot isn't bound- * by a timer that already expired before hydration got a chance to run.- */-export const scopedIntrospectionReady = (): Promise<void> => {- if (!isTimeoutArmed) {- isTimeoutArmed = true- setTimeout(markScopedIntrospectionReady, READY_TIMEOUT_MS)- }- return readyPromise-}--/**- * Syncs the flag's current value into `isScopedIntrospection()`. Call once- * near the root, under `FeatureFlagProviderWithOrgContext` (currently- * `DefaultLayout`).- */-export const useSyncScopedIntrospection = () => {- const { hasLoaded } = useFeatureFlags()- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)-- useEffect(() => {- setScopedIntrospection(scoped)-- // Self-hosted disables the flag provider (enabled={IS_PLATFORM}), so- // hasLoaded never flips true -- there's nothing to wait for there.- if (hasLoaded || !IS_PLATFORM) {- markScopedIntrospectionReady()- }- }, [scoped, hasLoaded])-}diff --git a/apps/studio/data/table-editor/table-editor-query.ts b/apps/studio/data/table-editor/table-editor-query.tsindex 6cd8cf37aa5..75e62ab6843 100644--- a/apps/studio/data/table-editor/table-editor-query.ts+++ b/apps/studio/data/table-editor/table-editor-query.ts@@ -1,17 +1,13 @@import { getTableEditorSql } from '@supabase/pg-meta'import { QueryClient, queryOptions, useQuery } from '@tanstack/react-query'-import { useFlag } from 'common'import { tableEditorKeys } from './keys'import { Entity } from './table-editor-types'import { executeSql } from '@/data/sql/execute-sql-mutation'import { ResponseError, UseCustomQueryOptions } from '@/types'-export const PG_META_SCOPED_INTROSPECTION_FLAG = 'pgMetaScopedIntrospection'-type TableEditorArgs = {id?: number- scoped?: boolean}export type TableEditorVariables = TableEditorArgs & {@@ -20,14 +16,14 @@ export type TableEditorVariables = TableEditorArgs & {}export async function getTableEditor(- { projectRef, connectionString, id, scoped = false }: TableEditorVariables,+ { projectRef, connectionString, id }: TableEditorVariables,signal?: AbortSignal) {if (!id) {throw new Error('id is required')}- const sql = getTableEditorSql({ id, scoped })+ const sql = getTableEditorSql({ id })const { result } = await executeSql({projectRef,@@ -51,10 +47,8 @@ export const useTableEditorQuery = <TData = TableEditorData>(...options}: UseCustomQueryOptions<TableEditorData, TableEditorError, TData> = {}) => {- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)-return useQuery<TableEditorData, TableEditorError, TData>({- ...tableEditorQueryOptions({ projectRef, connectionString, id, scoped }),+ ...tableEditorQueryOptions({ projectRef, connectionString, id }),enabled:enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id),refetchOnWindowFocus: false,@@ -66,19 +60,18 @@ export const useTableEditorQuery = <TData = TableEditorData>(export function prefetchTableEditor(client: QueryClient,- { projectRef, connectionString, id, scoped }: TableEditorVariables+ { projectRef, connectionString, id }: TableEditorVariables) {- return client.fetchQuery(tableEditorQueryOptions({ projectRef, connectionString, id, scoped }))+ return client.fetchQuery(tableEditorQueryOptions({ projectRef, connectionString, id }))}export const tableEditorQueryOptions = <TData = TableEditorData>({projectRef,connectionString,id,- scoped,}: TableEditorVariables) => {return queryOptions<TableEditorData, TableEditorError, TData>({- queryKey: [...tableEditorKeys.tableEditor(projectRef, id), { scoped: !!scoped }],- queryFn: ({ signal }) => getTableEditor({ projectRef, connectionString, id, scoped }, signal),+ queryKey: tableEditorKeys.tableEditor(projectRef, id),+ queryFn: ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal),})}diff --git a/apps/studio/data/table-rows/table-rows-count-query.ts b/apps/studio/data/table-rows/table-rows-count-query.tsindex c8aa1dfa45a..fa961af0ddb 100644--- a/apps/studio/data/table-rows/table-rows-count-query.ts+++ b/apps/studio/data/table-rows/table-rows-count-query.ts@@ -2,17 +2,14 @@ import { getTableRowsCountSql } from '@supabase/pg-meta'import { formatPatternMatchFilterValue } from '@supabase/pg-meta/src/query/table-row-query'import { PermissionAction } from '@supabase/shared-types/out/constants'import { QueryClient, useQuery, useQueryClient } from '@tanstack/react-query'-import { IS_PLATFORM, useFlag } from 'common'+import { IS_PLATFORM } from 'common'import { tableRowKeys } from './keys'import { parseSupaTable } from '@/components/grid/SupabaseGrid.utils'import type { Filter, SupaTable } from '@/components/grid/types'import { useConnectionStringForReadOps } from '@/data/read-replicas/replicas-query'import { executeSql } from '@/data/sql/execute-sql-mutation'-import {- PG_META_SCOPED_INTROSPECTION_FLAG,- prefetchTableEditor,-} from '@/data/table-editor/table-editor-query'+import { prefetchTableEditor } from '@/data/table-editor/table-editor-query'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { RoleImpersonationState, wrapWithRoleImpersonation } from '@/lib/role-impersonation'import { isRoleImpersonationEnabled } from '@/state/role-impersonation-state'@@ -35,7 +32,6 @@ export type TableRowsCountVariables = Omit<GetTableRowsCountArgs, 'table'> & {roleImpersonationState?: RoleImpersonationStateprojectRef?: stringconnectionString?: string | null- scoped?: boolean}export type TableRowsCountData = TableRowsCount@@ -51,7 +47,6 @@ export async function getTableRowsCount(roleImpersonationState,enforceExactCount,isReadOnlyContext = false,- scoped,}: TableRowsCountVariables & { isReadOnlyContext?: boolean },signal?: AbortSignal) {@@ -59,7 +54,6 @@ export async function getTableRowsCount(projectRef,connectionString,id: tableId,- scoped,})if (!entity) {throw new Error('Table not found')@@ -77,7 +71,6 @@ export async function getTableRowsCount(filters: formattedFilters,enforceExactCount,isReadOnlyContext,- scoped,}),roleImpersonationState)@@ -119,14 +112,12 @@ export const useTableRowsCountQuery = <TData = TableRowsCountData>(PermissionAction.TENANT_SQL_ADMIN_WRITE,'tables')- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)return useQuery<TableRowsCountData, TableRowsCountError, TData>({queryKey: tableRowKeys.tableRowsCount(projectRef, {table: { id: tableId },readReplicaIdentifier,...args,- scoped,}),queryFn: ({ signal }) =>getTableRowsCount(@@ -137,7 +128,6 @@ export const useTableRowsCountQuery = <TData = TableRowsCountData>(tableId,isReadOnlyContext: type === 'replica' || !canSQLAdminWrite,...args,- scoped,},signal),@@ -150,7 +140,7 @@ export const useTableRowsCountQuery = <TData = TableRowsCountData>(// read replicas it's already known synchronously, but otherwise it depends on// canSQLAdminWrite, which starts out `false` while permissions are loading.// Firing while that's still in flight would cache a transient- // isReadOnlyContext:true (and, on a never-analyzed table, a scoped+ // isReadOnlyContext:true (and, on a never-analyzed table,// count:-1/is_estimate:true) for what may actually be a writable user. Wait// for the permission check to settle before firing in that case.(type === 'replica' || !isPermissionsLoading),diff --git a/apps/studio/data/table-rows/table-rows-query.ts b/apps/studio/data/table-rows/table-rows-query.tsindex 9c04104a3a3..0df974a02d3 100644--- a/apps/studio/data/table-rows/table-rows-query.ts+++ b/apps/studio/data/table-rows/table-rows-query.ts@@ -5,7 +5,7 @@ import {getTableRowsSql,} from '@supabase/pg-meta/src/query/table-row-query'import { useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'-import { IS_PLATFORM, useFlag } from 'common'+import { IS_PLATFORM } from 'common'import { tableRowKeys } from './keys'import { parseSupaTable } from '@/components/grid/SupabaseGrid.utils'@@ -14,10 +14,7 @@ import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'import { handleError } from '@/data/fetchers'import { useConnectionStringForReadOps } from '@/data/read-replicas/replicas-query'import { executeSql } from '@/data/sql/execute-sql-mutation'-import {- PG_META_SCOPED_INTROSPECTION_FLAG,- prefetchTableEditor,-} from '@/data/table-editor/table-editor-query'+import { prefetchTableEditor } from '@/data/table-editor/table-editor-query'import { isMsSqlForeignTable } from '@/data/table-editor/table-editor-types'import { timeout } from '@/lib/helpers'import { RoleImpersonationState, wrapWithRoleImpersonation } from '@/lib/role-impersonation'@@ -31,7 +28,6 @@ interface GetTableRowsArgs {limit?: numberpage?: numberroleImpersonationState?: RoleImpersonationState- scoped?: boolean}/**@@ -336,7 +332,6 @@ async function getTableRows(limit,page,preflightCheck = false,- scoped,}: TableRowsVariables,signal?: AbortSignal) {@@ -344,7 +339,6 @@ async function getTableRows(projectRef,connectionString,id: tableId,- scoped,})if (!entity) {throw new Error('Table not found')@@ -405,7 +399,6 @@ export const useTableRowsQuery = <TData = TableRowsData>() => {const queryClient = useQueryClient()const { connectionString, identifier: readReplicaIdentifier } = useConnectionStringForReadOps()- const scoped = useFlag(PG_META_SCOPED_INTROSPECTION_FLAG)// [Ali] Exclude preflightCheck from query key — it controls how the query// executes (whether an EXPLAIN guard runs first), not what data is returned.@@ -416,10 +409,9 @@ export const useTableRowsQuery = <TData = TableRowsData>(table: { id: tableId },readReplicaIdentifier,...queryKeyArgs,- scoped,}),queryFn: ({ signal }) =>- getTableRows({ queryClient, projectRef, connectionString, tableId, ...args, scoped }, signal),+ getTableRows({ queryClient, projectRef, connectionString, tableId, ...args }, signal),enabled:enabled &&typeof projectRef !== 'undefined' &&diff --git a/apps/studio/data/tables/table-retrieve-query.ts b/apps/studio/data/tables/table-retrieve-query.tsindex 55e855238f3..1b71a2598fa 100644--- a/apps/studio/data/tables/table-retrieve-query.ts+++ b/apps/studio/data/tables/table-retrieve-query.ts@@ -3,7 +3,6 @@ import { useQuery } from '@tanstack/react-query'import { tableKeys } from './keys'import { getQueryClient } from '@/data/query-client'-import { isScopedIntrospection, scopedIntrospectionReady } from '@/data/scoped-introspection'import { executeSql } from '@/data/sql/execute-sql-mutation'import type { SafePostgresTable } from '@/lib/postgres-types'import type { ResponseError, UseCustomQueryOptions } from '@/types'@@ -19,9 +18,7 @@ export async function getTable({ projectRef, connectionString, name, schema }: TablesVariables,signal?: AbortSignal): Promise<SafePostgresTable> {- // Cold-load race guard -- see the module comment on scoped-introspection.ts.- await scopedIntrospectionReady()- const { sql, zod } = pgMeta.tables.retrieve({ name, schema, scoped: isScopedIntrospection() })+ const { sql, zod } = pgMeta.tables.retrieve({ name, schema })const { result } = await executeSql({diff --git a/packages/pg-meta/src/pg-meta-column-privileges.ts b/packages/pg-meta/src/pg-meta-column-privileges.tsindex ca331e3a8b2..7df09713f76 100644--- a/packages/pg-meta/src/pg-meta-column-privileges.ts+++ b/packages/pg-meta/src/pg-meta-column-privileges.ts@@ -1,7 +1,5 @@import { z } from 'zod'-import { DEFAULT_SYSTEM_SCHEMAS } from './constants'-import { filterByList } from './helpers'import {ident,joinSqlFragments,@@ -10,7 +8,7 @@ import {safeSql,type SafeSqlFragment,} from './pg-format'-import { COLUMN_PRIVILEGES_SQL, getScopedColumnPrivilegesSql } from './sql/column-privileges'+import { getScopedColumnPrivilegesSql } from './sql/column-privileges'const pgColumnPrivilegeGrant = z.object({grantor: z.string(),@@ -53,7 +51,6 @@ function list({relationName,limit,offset,- scoped = false,}: {includeSystemSchemas?: booleanincludedSchemas?: string[]@@ -63,76 +60,30 @@ function list({relationName?: stringlimit?: numberoffset?: number- scoped?: boolean} = {}): {sql: SafeSqlFragmentzod: typeof pgColumnPrivilegesArrayZod} {- // Scoped path: the base query prunes pg_class to the requested relations- // before exploding ACLs across their columns, instead of exploding the whole- // catalog and filtering the aggregate.- if (scoped) {- const base = getScopedColumnPrivilegesSql({- includeSystemSchemas,- includedSchemas,- excludedSchemas,- relationName,- // `columnIds` are "<attrelid>.<attnum>" pairs. Their relation half narrows- // the base scan; the exact attnum half stays an outer predicate below.- relationIds: columnIds?.length- ? [...new Set(columnIds.map((columnId) => columnId.split('.')[0]))]- : undefined,- })-- let sql = safeSql`- with column_privileges as (${base})- select *- from column_privileges- `- if (columnIds?.length) {- sql = safeSql`${sql} where column_id in (${joinSqlFragments(columnIds.map(literal), ',')})`- }- if (limit) {- sql = safeSql`${sql} limit ${literal(limit)}`- }- if (offset) {- sql = safeSql`${sql} offset ${literal(offset)}`- }- return {- sql,- zod: pgColumnPrivilegesArrayZod,- }- }+ const base = getScopedColumnPrivilegesSql({+ includeSystemSchemas,+ includedSchemas,+ excludedSchemas,+ relationName,+ // `columnIds` are "<attrelid>.<attnum>" pairs. Their relation half narrows+ // the base scan; the exact attnum half stays an outer predicate below.+ relationIds: columnIds?.length+ ? [...new Set(columnIds.map((columnId) => columnId.split('.')[0]))]+ : undefined,+ })let sql = safeSql`- with column_privileges as (${COLUMN_PRIVILEGES_SQL})+ with column_privileges as (${base})select *from column_privileges`-- const conditions: SafeSqlFragment[] = []-- const filter = filterByList(- includedSchemas,- excludedSchemas,- !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined- )- if (filter) {- conditions.push(safeSql`relation_schema ${filter}`)- }-- if (relationName) {- conditions.push(safeSql`relation_name = ${literal(relationName)}`)- }-if (columnIds?.length) {- conditions.push(safeSql`column_id in (${joinSqlFragments(columnIds.map(literal), ',')})`)+ sql = safeSql`${sql} where column_id in (${joinSqlFragments(columnIds.map(literal), ',')})`}-- if (conditions.length > 0) {- sql = safeSql`${sql} where ${joinSqlFragments(conditions, ' and ')}`- }-if (limit) {sql = safeSql`${sql} limit ${literal(limit)}`}diff --git a/packages/pg-meta/src/pg-meta-table-privileges.ts b/packages/pg-meta/src/pg-meta-table-privileges.tsindex aaea39c3531..c1ea141a87b 100644--- a/packages/pg-meta/src/pg-meta-table-privileges.ts+++ b/packages/pg-meta/src/pg-meta-table-privileges.ts@@ -10,7 +10,7 @@ import {safeSql,type SafeSqlFragment,} from './pg-format'-import { getScopedTablePrivilegesSql, TABLE_PRIVILEGES_SQL } from './sql/table-privileges'+import { getScopedTablePrivilegesSql } from './sql/table-privileges'const pgTablePrivilegesZod = z.object({relation_id: z.number(),@@ -50,14 +50,12 @@ function list({excludedSchemas,limit,offset,- scoped = false,}: {includeSystemSchemas?: booleanincludedSchemas?: string[]excludedSchemas?: string[]limit?: numberoffset?: number- scoped?: boolean} = {}): {sql: SafeSqlFragmentzod: typeof pgTablePrivilegesArrayZod@@ -67,34 +65,13 @@ function list({excludedSchemas,!includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined)- // Scoped path: push the schema filter into the base query's WHERE (before the- // aclexplode lateral / GROUP BY) instead of filtering the aggregated CTE.- if (scoped) {- const base = getScopedTablePrivilegesSql(filter ? safeSql`and nc.nspname ${filter}` : undefined)- let sql = safeSql`-with table_privileges as (${base})-select *-from table_privileges-`- if (limit) {- sql = safeSql`${sql} limit ${literal(limit)}`- }- if (offset) {- sql = safeSql`${sql} offset ${literal(offset)}`- }- return {- sql,- zod: pgTablePrivilegesArrayZod,- }- }+ // Push the schema filter into the base WHERE (before aclexplode / GROUP BY).+ const base = getScopedTablePrivilegesSql(filter ? safeSql`and nc.nspname ${filter}` : undefined)let sql = safeSql`-with table_privileges as (${TABLE_PRIVILEGES_SQL})+with table_privileges as (${base})select *from table_privileges`- if (filter) {- sql = safeSql`${sql} where schema ${filter}`- }if (limit) {sql = safeSql`${sql} limit ${literal(limit)}`}@@ -107,11 +84,11 @@ from table_privileges}}-function retrieve({ id, scoped }: { id: number; scoped?: boolean }): {+function retrieve({ id }: { id: number }): {sql: SafeSqlFragmentzod: typeof pgTablePrivilegesOptionalZod}-function retrieve({ name, schema, scoped }: { name: string; schema?: string; scoped?: boolean }): {+function retrieve({ name, schema }: { name: string; schema?: string }): {sql: SafeSqlFragmentzod: typeof pgTablePrivilegesOptionalZod}@@ -119,55 +96,25 @@ function retrieve({id,name,schema = 'public',- scoped = false,}: {id?: numbername?: stringschema?: string- scoped?: boolean}): {sql: SafeSqlFragmentzod: typeof pgTablePrivilegesOptionalZod} {- // Scoped path: push the oid / schema+name predicate into the base query's- // WHERE (before the aclexplode lateral / GROUP BY) so pg_class is pruned to- // the target relation instead of scanning every relation then filtering.- if (scoped) {- const scopeFilter = id- ? safeSql`and c.oid = ${literal(id)}`- : safeSql`and nc.nspname = ${literal(schema)} and c.relname = ${literal(name)}`- const sql = /* SQL */ safeSql`+ const scopeFilter = id+ ? safeSql`and c.oid = ${literal(id)}`+ : safeSql`and nc.nspname = ${literal(schema)} and c.relname = ${literal(name)}`+ const sql = /* SQL */ safeSql`with table_privileges as (${getScopedTablePrivilegesSql(scopeFilter)})select *from table_privileges`- return {- sql,- zod: pgTablePrivilegesOptionalZod,- }- }- if (id) {- const sql = /* SQL */ safeSql`-with table_privileges as (${TABLE_PRIVILEGES_SQL})-select *-from table_privileges-where table_privileges.relation_id = ${literal(id)};`- return {- sql,- zod: pgTablePrivilegesOptionalZod,- }- } else {- const sql = /* SQL */ safeSql`-with table_privileges as (${TABLE_PRIVILEGES_SQL})-select *-from table_privileges-where table_privileges.schema = ${literal(schema)}- and table_privileges.name = ${literal(name)}-`- return {- sql,- zod: pgTablePrivilegesOptionalZod,- }+ return {+ sql,+ zod: pgTablePrivilegesOptionalZod,}}diff --git a/packages/pg-meta/src/pg-meta-tables.ts b/packages/pg-meta/src/pg-meta-tables.tsindex 7209b51ae97..4e3026e6e1f 100644--- a/packages/pg-meta/src/pg-meta-tables.ts+++ b/packages/pg-meta/src/pg-meta-tables.ts@@ -115,49 +115,33 @@ function list<T extends boolean | undefined = true>(}}-function retrieve(identifier: TableIdentifier & { scoped?: boolean }): {+function retrieve(identifier: TableIdentifier): {sql: SafeSqlFragmentzod: z.ZodType<TableWithColumns>} {- let whereClause = getIdentifierWhereClause(identifier)+ const whereClause = getIdentifierWhereClause(identifier)- // Scoped path: resolve the target relation's OID once (via pg_class's- // (relname, relnamespace) index for the name+schema branch, or the literal- // for the id branch) and push it into BOTH enrichment CTEs, so the query- // computes sizes / PKs / relationships / columns only for the requested- // relation instead of the entire catalog (which timed out at ~58s on a- // hundreds-of-schemas database). Output rows are identical -- the legacy outer- // identifier filter already restricted the result to this relation.- if (identifier.scoped) {- // Resolve the target OID as a scalar the planner evaluates once (initplan):- // a literal for the id branch, or an uncorrelated scalar subquery resolving- // via pg_class's (relname, relnamespace) index for the name+schema branch.- let targetOid: SafeSqlFragment- if ('id' in identifier && identifier.id) {- targetOid = safeSql`${literal(identifier.id)}`- } else if ('name' in identifier && identifier.name && identifier.schema) {- targetOid = safeSql`(select tc.oid from pg_class tc join pg_namespace tn on tn.oid = tc.relnamespace where tc.relname = ${literal(identifier.name)} and tn.nspname = ${literal(identifier.schema)})`- } else {- throw new Error('Must provide either id or name and schema')- }- const scopedTables = getTablesSql(targetOid)- const scopedColumns = getColumnsSql({- filter: { column: 'oid', predicate: safeSql`= ${targetOid}` },- })- const sql = safeSql`+ // Resolve the target OID once (initplan) and push it into both enrichment+ // CTEs so sizes / PKs / relationships / columns are for this relation only.+ let targetOid: SafeSqlFragment+ if ('id' in identifier && identifier.id) {+ targetOid = safeSql`${literal(identifier.id)}`+ } else if ('name' in identifier && identifier.name && identifier.schema) {+ targetOid = safeSql`(select tc.oid from pg_class tc join pg_namespace tn on tn.oid = tc.relnamespace where tc.relname = ${literal(identifier.name)} and tn.nspname = ${literal(identifier.schema)})`+ } else {+ throw new Error('Must provide either id or name and schema')+ }+ const scopedTables = getTablesSql(targetOid)+ const scopedColumns = getColumnsSql({+ filter: { column: 'oid', predicate: safeSql`= ${targetOid}` },+ })+ const sql = safeSql`with tables as (${scopedTables}), columns as (${scopedColumns})select*, ${coalesceRowsToArray('columns', safeSql`columns.table_id = tables.id`, safeSql`columns.ordinal_position`)}from tables where ${whereClause};`- return {- sql,- zod: pgTableZod,- }- }-- const sql = safeSql`${generateEnrichedTablesSql({ includeColumns: true })} where ${whereClause};`return {sql,zod: pgTableZod,diff --git a/packages/pg-meta/src/pg-meta-types.ts b/packages/pg-meta/src/pg-meta-types.tsindex 6185b4ac205..61930d4efce 100644--- a/packages/pg-meta/src/pg-meta-types.ts+++ b/packages/pg-meta/src/pg-meta-types.ts@@ -3,7 +3,7 @@ import { z } from 'zod'import { DEFAULT_SYSTEM_SCHEMAS } from './constants'import { filterByList } from './helpers'import { literal, safeSql, type SafeSqlFragment } from './pg-format'-import { SCOPED_TYPES_SQL, TYPES_SQL } from './sql/types'+import { TYPES_SQL } from './sql/types'const pgTypeZod = z.object({id: z.number(),@@ -30,7 +30,6 @@ function list({excludedSchemas,limit,offset,- scoped = false,}: {includeArrayTypes?: booleanincludeSystemSchemas?: boolean@@ -38,15 +37,11 @@ function list({excludedSchemas?: string[]limit?: numberoffset?: number- scoped?: boolean} = {}): {sql: SafeSqlFragmentzod: typeof pgTypeArrayZod} {- // Both bases end at the same trailing WHERE `)`, so the filter/limit fragments- // below extend the same single-level WHERE regardless of which base is used.- // scoped=false keeps the rendered SQL byte-identical to the pre-change query.- let sql = scoped ? SCOPED_TYPES_SQL : TYPES_SQL+ let sql = TYPES_SQLif (!includeArrayTypes) {sql = safeSql`${sql} and not exists (select from pg_type el@@ -62,11 +57,7 @@ function list({if (filter) {sql = safeSql`${sql} and n.nspname ${filter}`}- if (scoped) {- // Scoped only: legacy TYPES_SQL has no ORDER BY (plan-dependent order); sort- // the scoped result by t.oid for a stable, comparable order. Before LIMIT.- sql = safeSql`${sql} order by t.oid`- }+ sql = safeSql`${sql} order by t.oid`if (limit) {sql = safeSql`${sql} limit ${literal(limit)}`}diff --git a/packages/pg-meta/src/sql/column-privileges.ts b/packages/pg-meta/src/sql/column-privileges.tsindex fd6b3e2813d..232bb5e99c4 100644--- a/packages/pg-meta/src/sql/column-privileges.ts+++ b/packages/pg-meta/src/sql/column-privileges.ts@@ -2,158 +2,6 @@ import { DEFAULT_SYSTEM_SCHEMAS } from '../constants'import { filterByList } from '../helpers'import { joinSqlFragments, literal, safeSql, type SafeSqlFragment } from '../pg-format'-export const COLUMN_PRIVILEGES_SQL = /* SQL */ safeSql`--- FROZEN legacy path: served while the pgMetaScopedIntrospection flag is off.--- Do not edit -- it must keep matching production behavior until the flag--- cleanup deletes it. getScopedColumnPrivilegesSql is the replacement.------ Lists each column's privileges in the form of:------ [--- {--- "column_id": "12345.1",--- "relation_schema": "public",--- "relation_name": "mytable",--- "column_name": "mycolumn",--- "privileges": [--- {--- "grantor": "postgres",--- "grantee": "myrole",--- "privilege_type": "SELECT",--- "is_grantable": false--- },--- ...--- ]--- },--- ...--- ]------ Modified from information_schema.column_privileges. We try to be as close as--- possible to the view definition, obtained from:------ select pg_get_viewdef('information_schema.column_privileges');------ The main differences are:--- - we include column privileges for materialized views--- (reason for exclusion in information_schema.column_privileges:--- https://www.postgresql.org/message-id/9136.1502740844%40sss.pgh.pa.us)--- - we query a.attrelid and a.attnum to generate column_id--- - table_catalog is omitted--- - table_schema -> relation_schema, table_name -> relation_name------ Column privileges are intertwined with table privileges in that table--- privileges override column privileges. E.g. if we do:------ grant all on mytable to myrole;------ Then myrole is granted privileges for ALL columns. Likewise, if we do:------ grant all (id) on mytable to myrole;--- revoke all on mytable from myrole;------ Then the grant on the id column is revoked.------ This is unlike how grants for schemas and tables interact, where you need--- privileges for BOTH the schema the table is in AND the table itself in order--- to access the table.--select (x.attrelid || '.' || x.attnum) as column_id,- nc.nspname as relation_schema,- x.relname as relation_name,- x.attname as column_name,- coalesce(- jsonb_agg(- jsonb_build_object(- 'grantor', u_grantor.rolname,- 'grantee', grantee.rolname,- 'privilege_type', x.prtype,- 'is_grantable', x.grantable- )- ),- '[]'- ) as privileges-from- (select pr_c.grantor,- pr_c.grantee,- a.attrelid,- a.attnum,- a.attname,- pr_c.relname,- pr_c.relnamespace,- pr_c.prtype,- pr_c.grantable,- pr_c.relowner- from- (select pg_class.oid,- pg_class.relname,- pg_class.relnamespace,- pg_class.relowner,- (aclexplode(coalesce(pg_class.relacl, acldefault('r', pg_class.relowner)))).grantor as grantor,- (aclexplode(coalesce(pg_class.relacl, acldefault('r', pg_class.relowner)))).grantee as grantee,- (aclexplode(coalesce(pg_class.relacl, acldefault('r', pg_class.relowner)))).privilege_type as privilege_type,- (aclexplode(coalesce(pg_class.relacl, acldefault('r', pg_class.relowner)))).is_grantable as is_grantable- from pg_class- where (pg_class.relkind = any (array['r',- 'v',- 'm',- 'f',- 'p'])) ) pr_c(oid, relname, relnamespace, relowner, grantor, grantee, prtype, grantable),- pg_attribute a- where ((a.attrelid = pr_c.oid)- and (a.attnum > 0)- and (not a.attisdropped))- union select pr_a.grantor,- pr_a.grantee,- pr_a.attrelid,- pr_a.attnum,- pr_a.attname,- c.relname,- c.relnamespace,- pr_a.prtype,- pr_a.grantable,- c.relowner- from- (select a.attrelid,- a.attnum,- a.attname,- (aclexplode(coalesce(a.attacl, acldefault('c', cc.relowner)))).grantor as grantor,- (aclexplode(coalesce(a.attacl, acldefault('c', cc.relowner)))).grantee as grantee,- (aclexplode(coalesce(a.attacl, acldefault('c', cc.relowner)))).privilege_type as privilege_type,- (aclexplode(coalesce(a.attacl, acldefault('c', cc.relowner)))).is_grantable as is_grantable- from (pg_attribute a- join pg_class cc on ((a.attrelid = cc.oid)))- where ((a.attnum > 0)- and (not a.attisdropped))) pr_a(attrelid, attnum, attname, grantor, grantee, prtype, grantable),- pg_class c- where ((pr_a.attrelid = c.oid)- and (c.relkind = any (ARRAY['r',- 'v',- 'm',- 'f',- 'p'])))) x,- pg_namespace nc,- pg_authid u_grantor,- (select pg_authid.oid,- pg_authid.rolname- from pg_authid- union all select (0)::oid as oid,- 'PUBLIC') grantee(oid, rolname)-where ((x.relnamespace = nc.oid)- and (x.grantee = grantee.oid)- and (x.grantor = u_grantor.oid)- and (x.prtype = any (ARRAY['INSERT',- 'SELECT',- 'UPDATE',- 'REFERENCES']))- and (pg_has_role(u_grantor.oid, 'USAGE')- or pg_has_role(grantee.oid, 'USAGE')- or (grantee.rolname = 'PUBLIC')))-group by column_id,- nc.nspname,- x.relname,- x.attname-`-export type ColumnPrivilegesScope = {/** Defaults to false, which excludes {@link DEFAULT_SYSTEM_SCHEMAS}. */includeSystemSchemas?: boolean@@ -166,9 +14,8 @@ export type ColumnPrivilegesScope = {}/**- * Scoped variant of {@link COLUMN_PRIVILEGES_SQL}: prunes pg_class/pg_namespace- * FIRST (in the `rel` CTE) so the scope predicate can drive an index scan,- * instead of aclexploding the whole catalog and filtering the aggregated result.+ * Column ACLs. Prunes pg_class/pg_namespace in the `rel` CTE first so the+ * scope predicate can drive an index scan.*/export const getScopedColumnPrivilegesSql = ({includeSystemSchemas = false,diff --git a/packages/pg-meta/src/sql/studio/database/get-count-estimate.ts b/packages/pg-meta/src/sql/studio/database/get-count-estimate.tsindex 6a265bee4cb..85fece2c6cb 100644--- a/packages/pg-meta/src/sql/studio/database/get-count-estimate.ts+++ b/packages/pg-meta/src/sql/studio/database/get-count-estimate.ts@@ -12,9 +12,6 @@ export const THRESHOLD_COUNT = 50000*/export const THRESHOLD_ESTIMATE_BYTES = THRESHOLD_COUNT * 200-// FROZEN legacy path: served while the pgMetaScopedIntrospection flag is off.-// Do not edit -- it must keep matching production behavior until the flag-// cleanup deletes it. The scoped path reuses this same function.export const COUNT_ESTIMATE_SQL: SafeSqlFragment = safeSql`CREATE OR REPLACE FUNCTION pg_temp.count_estimate(query textdiff --git a/packages/pg-meta/src/sql/studio/database/rows.ts b/packages/pg-meta/src/sql/studio/database/rows.tsindex 8c826168a38..8e01da493f7 100644--- a/packages/pg-meta/src/sql/studio/database/rows.ts+++ b/packages/pg-meta/src/sql/studio/database/rows.ts@@ -3,27 +3,23 @@ import { Filter, Query } from '../../../query'import { COUNT_ESTIMATE_SQL, THRESHOLD_COUNT, THRESHOLD_ESTIMATE_BYTES } from './get-count-estimate'/**- * Row-count for a table. reltuples = -1 (never analyzed) covers BOTH an- * empty/small new table and a freshly bulk-loaded huge one, so the opt-in- * `scoped` path gates on the real heap size (pg_relation_size, + pg_partition_tree- * sum for partitioned parents whose own size is 0; relpages is equally stale- * pre-vacuum): large -> EXPLAIN estimate, small/empty -> exact count. scoped=false- * is byte-identical to the legacy query. Full matrix in rows-count.test.ts.+ * Row-count for a table. reltuples = -1 (never analyzed) covers both an+ * empty/small new table and a freshly bulk-loaded huge one, so we gate on+ * real heap size (pg_relation_size, + pg_partition_tree for partitioned+ * parents whose own size is 0): large -> EXPLAIN estimate, small/empty ->+ * exact count.*/export const getTableRowsCountSql = ({table,filters = [],enforceExactCount = false,isReadOnlyContext = false,- scoped = false,}: {table: anyfilters?: Filter[]enforceExactCount?: boolean- /** Skips using the count estimate function if true and fallsback to checking reltuples from pg_class */+ /** Skip creating pg_temp.count_estimate; fall back to pg_class.reltuples. */isReadOnlyContext?: boolean- /** Opt-in optimized counting; gates never-analyzed tables on real heap size. */- scoped?: boolean}): SafeSqlFragment => {if (!table) return safeSql``@@ -66,12 +62,10 @@ export const getTableRowsCountSql = ({: countBaseSqlif (isReadOnlyContext) {- if (scoped) {- // Readonly can't create the pg_temp function: an over-threshold or- // physically-large never-analyzed table reports -1 (is_estimate=true);- // a small/empty one still gets an exact count. CASE and flag share the- // condition.- const sql = safeSql`+ // Readonly can't create the pg_temp function: an over-threshold or+ // physically-large never-analyzed table reports -1 (is_estimate=true);+ // a small/empty one still gets an exact count.+ const sql = safeSql`with approximation as (selectreltuples as estimate,@@ -94,37 +88,15 @@ selectend as count,(estimate > ${literal(THRESHOLD_COUNT)} or (estimate = -1 and bytes > ${literal(THRESHOLD_ESTIMATE_BYTES)})) as is_estimatefrom approximation;-`-- return sql- }- // FROZEN legacy path (pgMetaScopedIntrospection off): do not edit -- it- // must keep matching production behavior until the flag cleanup deletes it.- const sql = safeSql`-with approximation as (- select reltuples as estimate- from pg_class- where oid = ${literal(table.id)}-)-select- case- when estimate > ${literal(THRESHOLD_COUNT)} then (select -1)- else (${countBaseSqlWithoutSemicolon})- end as count,- estimate > ${literal(THRESHOLD_COUNT)} as is_estimate-from approximation;`return sql} else {- if (scoped) {- // estimate = -1 (never analyzed) gated on heap size (see CTE): large ->- // EXPLAIN estimate, small/empty -> exact count (avoids Postgres's ~10-page- // phantom estimate). Over-threshold keeps legacy behavior. CASE and flag- // share the condition. literal() quotes the embedded select so backslash- // identifiers survive under any standard_conforming_strings.- const estimateExpr = safeSql`pg_temp.count_estimate(${literal(selectBaseSqlWithoutSemicolon)})`- const sql = safeSql`+ // estimate = -1 gated on heap size: large -> EXPLAIN estimate,+ // small/empty -> exact count. literal() quotes the embedded select so+ // backslash identifiers survive under any standard_conforming_strings.+ const estimateExpr = safeSql`pg_temp.count_estimate(${literal(selectBaseSqlWithoutSemicolon)})`+ const sql = safeSql`${COUNT_ESTIMATE_SQL}with approximation as (@@ -150,27 +122,6 @@ selectend as count,(estimate > ${literal(THRESHOLD_COUNT)} or (estimate = -1 and bytes > ${literal(THRESHOLD_ESTIMATE_BYTES)})) as is_estimatefrom approximation;-`-- return sql- }- // FROZEN legacy path (pgMetaScopedIntrospection off): do not edit -- it- // must keep matching production behavior until the flag cleanup deletes it.- const sql = safeSql`-${COUNT_ESTIMATE_SQL}--with approximation as (- select reltuples as estimate- from pg_class- where oid = ${literal(table.id)}-)-select- case- when estimate > ${literal(THRESHOLD_COUNT)} then ${filters.length > 0 ? safeSql`pg_temp.count_estimate('${selectBaseSqlWithoutSemicolon.replaceAll("'", "''") as SafeSqlFragment}')` : safeSql`estimate`}- else (${countBaseSqlWithoutSemicolon})- end as count,- estimate > ${literal(THRESHOLD_COUNT)} as is_estimate-from approximation;`return sqldiff --git a/packages/pg-meta/src/sql/studio/database/table-definition.ts b/packages/pg-meta/src/sql/studio/database/table-definition.tsindex 4fbda5ea0c2..d78f5bf6347 100644--- a/packages/pg-meta/src/sql/studio/database/table-definition.ts+++ b/packages/pg-meta/src/sql/studio/database/table-definition.ts@@ -11,718 +11,8 @@import { joinSqlFragments, literal, safeSql, type SafeSqlFragment } from '../../../pg-format'-/**- * Builds the CREATE (pg_temp) pg_get_tabledef function block.- *- * PR #47894 replaced three O(catalog) information_schema scans (and a- * relnamespace::regnamespace cast per pg_class row) with direct string tests- * and an OID-scoped partial-index lookup. That NEW behavior is gated behind- * `scoped` (default false = legacy behavior) so Studio can roll it out behind a- * feature flag. When `scoped` is false the emitted function is byte-equivalent- * to the pre-PR version.- *- * The two branches are kept as complete, standalone templates (no interpolated- * conditional fragments) so each rendered statement is easy to read and diff.- */-// FROZEN legacy path: served while the pgMetaScopedIntrospection flag is off.-// Do not edit -- it must keep matching production behavior until the flag-// cleanup deletes it. SCOPED_PG_GET_TABLEDEF_SQL is the replacement.-const LEGACY_PG_GET_TABLEDEF_SQL: SafeSqlFragment = safeSql`- DROP TYPE IF EXISTS pg_temp.tabledefs CASCADE;- CREATE TYPE pg_temp.tabledefs AS ENUM ('PKEY_INTERNAL','PKEY_EXTERNAL','FKEYS_INTERNAL', 'FKEYS_EXTERNAL', 'COMMENTS', 'FKEYS_NONE', 'INCLUDE_TRIGGERS', 'NO_TRIGGERS');-- -- SELECT * FROM pg_temp.pg_get_coldef('sample','orders','id');- -- DROP FUNCTION pg_temp.pg_get_coldef(text,text,text,boolean);- CREATE OR REPLACE FUNCTION pg_temp.pg_get_coldef(- in_schema text,- in_table text,- in_column text,- oldway boolean default False- )- RETURNS text- LANGUAGE plpgsql VOLATILE- AS- $$- DECLARE- v_coldef text;- v_dt1 text;- v_dt2 text;- v_dt3 text;- v_nullable boolean;- v_position int;- v_identity text;- v_generated text;- v_hasdflt boolean;- v_dfltexpr text;-- BEGIN- IF oldway THEN- SELECT pg_catalog.format_type(a.atttypid, a.atttypmod) INTO v_coldef FROM pg_namespace n, pg_class c, pg_attribute a, pg_type t- WHERE n.nspname = in_schema AND n.oid = c.relnamespace AND c.relname = in_table AND a.attname = in_column and a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid ORDER BY a.attnum;- -- RAISE NOTICE 'DEBUG: oldway=%',v_coldef;- ELSE- -- a.attrelid::regclass::text, a.attname- SELECT CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) AND EXISTS (SELECT FROM pg_attrdef ad WHERE ad.adrelid = a.attrelid AND ad.adnum = a.attnum AND- pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' || (pg_get_serial_sequence (a.attrelid::regclass::text, a.attname))::regclass || '''::regclass)') THEN CASE a.atttypid- WHEN 'int'::regtype THEN 'serial' WHEN 'int8'::regtype THEN 'bigserial' WHEN 'int2'::regtype THEN 'smallserial' END ELSE format_type(a.atttypid, a.atttypmod) END AS data_type- INTO v_coldef FROM pg_namespace n, pg_class c, pg_attribute a, pg_type t- WHERE n.nspname = in_schema AND n.oid = c.relnamespace AND c.relname = in_table AND a.attname = in_column and a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid ORDER BY a.attnum;- -- RAISE NOTICE 'DEBUG: newway=%',v_coldef;-- -- Issue#24: not implemented yet- -- might replace with this below to do more detailed parsing...- -- SELECT a.atttypid::regtype AS dt1, format_type(a.atttypid, a.atttypmod) as dt2, t.typname as dt3, CASE WHEN not(a.attnotnull) THEN True ELSE False END AS nullable,- -- a.attnum, a.attidentity, a.attgenerated, a.atthasdef, pg_get_expr(ad.adbin, ad.adrelid) dfltexpr- -- INTO v_dt1, v_dt2, v_dt3, v_nullable, v_position, v_identity, v_generated, v_hasdflt, v_dfltexpr- -- FROM pg_attribute a JOIN pg_class c ON (a.attrelid = c.oid) JOIN pg_type t ON (a.atttypid = t.oid) LEFT JOIN pg_attrdef ad ON (a.attrelid = ad.adrelid AND a.attnum = ad.adnum)- -- WHERE c.relkind in ('r','p') AND a.attnum > 0 AND NOT a.attisdropped AND c.relnamespace::regnamespace::text = in_schema AND c.relname = in_table AND a.attname = in_column;- -- RAISE NOTICE 'schema=% table=% column=% dt1=% dt2=% dt3=% nullable=% pos=% identity=% generated=% HasDefault=% DeftExpr=%', in_schema, in_table, in_column, v_dt1,v_dt2,v_dt3,v_nullable,v_position,v_identity,v_generated,v_hasdflt,v_dfltexpr;- END IF;- RETURN v_coldef;- END;- $$;-- -- SELECT * FROM pg_temp.pg_get_tabledef('sample', 'address', false);- DROP FUNCTION IF EXISTS pg_temp.pg_get_tabledef(character varying,character varying,boolean,tabledefs[]);- CREATE OR REPLACE FUNCTION pg_temp.pg_get_tabledef(- in_schema varchar,- in_table varchar,- _verbose boolean,- VARIADIC arr pg_temp.tabledefs[] DEFAULT '{}':: pg_temp.tabledefs[]- )- RETURNS text- LANGUAGE plpgsql VOLATILE- AS- $$- DECLARE- v_qualified text := '';- v_table_ddl text;- v_table_oid int;- v_colrec record;- v_constraintrec record;- v_trigrec record;- v_indexrec record;- v_rec record;- v_constraint_name text;- v_constraint_def text;- v_pkey_def text := '';- v_fkey_def text := '';- v_fkey_defs text := '';- v_trigger text := '';- v_partition_key text := '';- v_partbound text;- v_parent text;- v_parent_schema text;- v_persist text;- v_temp text := '';- v_temp2 text;- v_relopts text;- v_tablespace text;- v_pgversion int;- bSerial boolean;- bPartition boolean;- bInheritance boolean;- bRelispartition boolean;- constraintarr text[] := '{}';- constraintelement text;- bSkip boolean;- bVerbose boolean := False;- v_cnt1 integer;- v_cnt2 integer;- search_path_old text := '';- search_path_new text := '';- v_partial boolean;- v_pos integer;-- -- assume defaults for ENUMs at the getgo- pkcnt int := 0;- fkcnt int := 0;- trigcnt int := 0;- cmtcnt int := 0;- pktype pg_temp.tabledefs := 'PKEY_INTERNAL';- fktype pg_temp.tabledefs := 'FKEYS_INTERNAL';- trigtype pg_temp.tabledefs := 'NO_TRIGGERS';- arglen integer;- vargs text;- avarg pg_temp.tabledefs;-- -- exception variables- v_ret text;- v_diag1 text;- v_diag2 text;- v_diag3 text;- v_diag4 text;- v_diag5 text;- v_diag6 text;-- BEGIN- SET client_min_messages = 'notice';- IF _verbose THEN bVerbose = True; END IF;-- -- v17 fix: handle case-sensitive- -- v_qualified = in_schema || '.' || in_table;-- arglen := array_length($4, 1);- IF arglen IS NULL THEN- -- nothing to do, so assume defaults- NULL;- ELSE- -- loop thru args- -- IF 'NO_TRIGGERS' = ANY ($4)- -- select array_to_string($4, ',', '***') INTO vargs;- IF bVerbose THEN RAISE NOTICE 'arguments=%', $4; END IF;- FOREACH avarg IN ARRAY $4 LOOP- IF bVerbose THEN RAISE NOTICE 'arg=%', avarg; END IF;- IF avarg = 'FKEYS_INTERNAL' OR avarg = 'FKEYS_EXTERNAL' OR avarg = 'FKEYS_NONE' THEN- fkcnt = fkcnt + 1;- fktype = avarg;- ELSEIF avarg = 'INCLUDE_TRIGGERS' OR avarg = 'NO_TRIGGERS' THEN- trigcnt = trigcnt + 1;- trigtype = avarg;- ELSEIF avarg = 'PKEY_EXTERNAL' THEN- pkcnt = pkcnt + 1;- pktype = avarg;- ELSEIF avarg = 'COMMENTS' THEN- cmtcnt = cmtcnt + 1;-- END IF;- END LOOP;- IF fkcnt > 1 THEN- RAISE WARNING 'Only one foreign key option can be provided. You provided %', fkcnt;- RETURN '';- ELSEIF trigcnt > 1 THEN- RAISE WARNING 'Only one trigger option can be provided. You provided %', trigcnt;- RETURN '';- ELSEIF pkcnt > 1 THEN- RAISE WARNING 'Only one pkey option can be provided. You provided %', pkcnt;- RETURN '';- ELSEIF cmtcnt > 1 THEN- RAISE WARNING 'Only one comments option can be provided. You provided %', cmtcnt;- RETURN '';-- END IF;- END IF;-- SELECT c.oid, (select setting from pg_settings where name = 'server_version_num') INTO v_table_oid, v_pgversion FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace- WHERE c.relkind in ('r','p') AND c.relname = in_table AND n.nspname = in_schema;-- -- set search_path = public before we do anything to force explicit schema qualification but dont forget to set it back before exiting...- SELECT setting INTO search_path_old FROM pg_settings WHERE name = 'search_path';-- -- RAISE NOTICE 'DEBUG tableddl: saving old search_path: ***%***', search_path_old;- EXECUTE 'SET search_path = "public"';- SELECT setting INTO search_path_new FROM pg_settings WHERE name = 'search_path';- -- RAISE NOTICE 'DEBUG tableddl: using new search path=***%***', search_path_new;-- -- throw an error if table was not found- IF (v_table_oid IS NULL) THEN- RAISE EXCEPTION 'table does not exist';- END IF;-- -- get user-defined tablespaces if applicable- SELECT tablespace INTO v_temp FROM pg_tables WHERE schemaname = in_schema and tablename = in_table and tablespace IS NOT NULL;- IF v_temp IS NULL THEN- v_tablespace := 'TABLESPACE pg_default';- ELSE- v_tablespace := 'TABLESPACE ' || v_temp;- END IF;-- -- also see if there are any SET commands for this table, ie, autovacuum_enabled=off, fillfactor=70- WITH relopts AS (SELECT unnest(c.reloptions) relopts FROM pg_class c, pg_namespace n WHERE n.nspname = in_schema and n.oid = c.relnamespace and c.relname = in_table)- SELECT string_agg(r.relopts, ', ') as relopts INTO v_temp from relopts r;- IF v_temp IS NULL THEN- v_relopts := '';- ELSE- v_relopts := ' WITH (' || v_temp || ')';- END IF;-- -- ------------------------------------------------------------------------------------ -- Create table defs for partitions/children using inheritance or declarative methods.- -- inheritance: pg_class.relkind = 'r' pg_class.relispartition=false pg_class.relpartbound is NULL- -- declarative: pg_class.relkind = 'r' pg_class.relispartition=true pg_class.relpartbound is NOT NULL- -- ------------------------------------------------------------------------------------ v_partbound := '';- bPartition := False;- bInheritance := False;- IF v_pgversion < 100000 THEN- -- Issue#11: handle parent schema- SELECT c2.relname parent, c2.relnamespace::regnamespace INTO v_parent, v_parent_schema from pg_class c1, pg_namespace n, pg_inherits i, pg_class c2- WHERE n.nspname = in_schema and n.oid = c1.relnamespace and c1.relname = in_table and c1.oid = i.inhrelid and i.inhparent = c2.oid and c1.relkind = 'r';- IF (v_parent IS NOT NULL) THEN- bPartition := True;- bInheritance := True;- END IF;- ELSE- -- Issue#11: handle parent schema- SELECT c2.relname parent, c1.relispartition, pg_get_expr(c1.relpartbound, c1.oid, true), c2.relnamespace::regnamespace INTO v_parent, bRelispartition, v_partbound, v_parent_schema from pg_class c1, pg_namespace n, pg_inherits i, pg_class c2- WHERE n.nspname = in_schema and n.oid = c1.relnamespace and c1.relname = in_table and c1.oid = i.inhrelid and i.inhparent = c2.oid and c1.relkind = 'r';- IF (v_parent IS NOT NULL) THEN- bPartition := True;- IF bRelispartition THEN- bInheritance := False;- ELSE- bInheritance := True;- END IF;- END IF;- END IF;- IF bPartition THEN- --Issue#17 fix for case-sensitive tables- -- SELECT count(*) INTO v_cnt1 FROM information_schema.tables t WHERE EXISTS (SELECT REGEXP_MATCHES(s.table_name, '([A-Z]+)','g') FROM information_schema.tables s- -- WHERE t.table_schema=s.table_schema AND t.table_name=s.table_name AND t.table_schema = quote_ident(in_schema) AND t.table_name = quote_ident(in_table) AND t.table_type = 'BASE TABLE');- SELECT count(*) INTO v_cnt1 FROM information_schema.tables t WHERE EXISTS (SELECT REGEXP_MATCHES(s.table_name, '([A-Z]+)','g') FROM information_schema.tables s- WHERE t.table_schema=s.table_schema AND t.table_name=s.table_name AND t.table_schema = in_schema AND t.table_name = in_table AND t.table_type = 'BASE TABLE');-- --Issue#19 put double-quotes around SQL keyword column names- -- Issue#121: fix keyword lookup for table name not column name that does not apply here- -- SELECT COUNT(*) INTO v_cnt2 FROM pg_get_keywords() WHERE word = v_colrec.column_name AND catcode = 'R';- SELECT COUNT(*) INTO v_cnt2 FROM pg_get_keywords() WHERE word = in_table AND catcode = 'R';-- IF bInheritance THEN- -- inheritance-based- IF v_cnt1 > 0 OR v_cnt2 > 0 THEN- v_table_ddl := 'CREATE TABLE ' || in_schema || '."' || in_table || '"( '|| E'\\n';- ELSE- v_table_ddl := 'CREATE TABLE ' || in_schema || '.' || in_table || '( '|| E'\\n';- END IF;-- -- Jump to constraints section to add the check constraints- ELSE- -- declarative-based- IF v_relopts <> '' THEN- IF v_cnt1 > 0 OR v_cnt2 > 0 THEN- v_table_ddl := 'CREATE TABLE ' || in_schema || '."' || in_table || '" PARTITION OF ' || in_schema || '.' || v_parent || ' ' || v_partbound || v_relopts || ' ' || v_tablespace || '; ' || E'\\n';- ELSE- v_table_ddl := 'CREATE TABLE ' || in_schema || '.' || in_table || ' PARTITION OF ' || in_schema || '.' || v_parent || ' ' || v_partbound || v_relopts || ' ' || v_tablespace || '; ' || E'\\n';- END IF;- ELSE- IF v_cnt1 > 0 OR v_cnt2 > 0 THEN- v_table_ddl := 'CREATE TABLE ' || in_schema || '."' || in_table || '" PARTITION OF ' || in_schema || '.' || v_parent || ' ' || v_partbound || ' ' || v_tablespace || '; ' || E'\\n';- ELSE- v_table_ddl := 'CREATE TABLE ' || in_schema || '.' || in_table || ' PARTITION OF ' || in_schema || '.' || v_parent || ' ' || v_partbound || ' ' || v_tablespace || '; ' || E'\\n';- END IF;- END IF;- -- Jump to constraints and index section to add the check constraints and indexes and perhaps FKeys- END IF;- END IF;- IF bVerbose THEN RAISE NOTICE '(1)tabledef so far: %', v_table_ddl; END IF;-- IF NOT bPartition THEN- -- see if this is unlogged or temporary table- select c.relpersistence into v_persist from pg_class c, pg_namespace n where n.nspname = in_schema and n.oid = c.relnamespace and c.relname = in_table and c.relkind = 'r';- IF v_persist = 'u' THEN- v_temp := 'UNLOGGED';- ELSIF v_persist = 't' THEN- v_temp := 'TEMPORARY';- ELSE- v_temp := '';- END IF;- END IF;-- -- start the create definition for regular tables unless we are in progress creating an inheritance-based child table- IF NOT bPartition THEN- --Issue#17 fix for case-sensitive tables- -- SELECT count(*) INTO v_cnt1 FROM information_schema.tables t WHERE EXISTS (SELECT REGEXP_MATCHES(s.table_name, '([A-Z]+)','g') FROM information_schema.tables s- -- WHERE t.table_schema=s.table_schema AND t.table_name=s.table_name AND t.table_schema = quote_ident(in_schema) AND t.table_name = quote_ident(in_table) AND t.table_type = 'BASE TABLE');- SELECT count(*) INTO v_cnt1 FROM information_schema.tables t WHERE EXISTS (SELECT REGEXP_MATCHES(s.table_name, '([A-Z]+)','g') FROM information_schema.tables s- WHERE t.table_schema=s.table_schema AND t.table_name=s.table_name AND t.table_schema = in_schema AND t.table_name = in_table AND t.table_type = 'BASE TABLE');- IF v_cnt1 > 0 THEN- v_table_ddl := 'CREATE ' || v_temp || ' TABLE ' || in_schema || '."' || in_table || '" (' || E'\\n';- ELSE- v_table_ddl := 'CREATE ' || v_temp || ' TABLE ' || in_schema || '.' || in_table || ' (' || E'\\n';- END IF;- END IF;- -- RAISE NOTICE 'DEBUG2: tabledef so far: %', v_table_ddl;- -- define all of the columns in the table unless we are in progress creating an inheritance-based child table- IF NOT bPartition THEN- FOR v_colrec IN- SELECT c.column_name, c.data_type, c.udt_name, c.udt_schema, c.character_maximum_length, c.is_nullable, c.column_default, c.numeric_precision, c.numeric_scale, c.is_identity, c.identity_generation, c.is_generated, c.generation_expression- FROM information_schema.columns c WHERE (table_schema, table_name) = (in_schema, in_table) ORDER BY ordinal_position- LOOP- IF bVerbose THEN RAISE NOTICE '(col loop) name=% type=% udt_name=% default=% is_generated=% gen_expr=%', v_colrec.column_name, v_colrec.data_type, v_colrec.udt_name, v_colrec.column_default, v_colrec.is_generated, v_colrec.generation_expression; END IF;-- -- v17 fix: handle case-sensitive for pg_get_serial_sequence that requires SQL Identifier handling- -- SELECT CASE WHEN pg_get_serial_sequence(v_qualified, v_colrec.column_name) IS NOT NULL THEN True ELSE False END into bSerial;- SELECT CASE WHEN pg_get_serial_sequence(quote_ident(in_schema) || '.' || quote_ident(in_table), v_colrec.column_name) IS NOT NULL THEN True ELSE False END into bSerial;- IF bVerbose THEN- -- v17 fix: handle case-sensitive for pg_get_serial_sequence that requires SQL Identifier handling- -- SELECT pg_get_serial_sequence(v_qualified, v_colrec.column_name) into v_temp;- SELECT pg_get_serial_sequence(quote_ident(in_schema) || '.' || quote_ident(in_table), v_colrec.column_name) into v_temp;- IF v_temp IS NULL THEN v_temp = 'NA'; END IF;- SELECT pg_temp.pg_get_coldef(in_schema, in_table,v_colrec.column_name) INTO v_diag1;- RAISE NOTICE 'DEBUG table: % Column: % datatype: % Serial=% serialval=% coldef=%', v_qualified, v_colrec.column_name, v_colrec.data_type, bSerial, v_temp, v_diag1;- RAISE NOTICE 'DEBUG tabledef: %', v_table_ddl;- END IF;-- --Issue#17 put double-quotes around case-sensitive column names- SELECT COUNT(*) INTO v_cnt1 FROM information_schema.columns t WHERE EXISTS (SELECT REGEXP_MATCHES(s.column_name, '([A-Z]+)','g') FROM information_schema.columns s- WHERE t.table_schema=s.table_schema and t.table_name=s.table_name and t.column_name=s.column_name AND t.table_schema = quote_ident(in_schema) AND column_name = v_colrec.column_name);-- --Issue#19 put double-quotes around SQL keyword column names- SELECT COUNT(*) INTO v_cnt2 FROM pg_get_keywords() WHERE word = v_colrec.column_name AND catcode = 'R';-- IF v_cnt1 > 0 OR v_cnt2 > 0 THEN- v_table_ddl := v_table_ddl || ' "' || v_colrec.column_name || '" ';- ELSE- v_table_ddl := v_table_ddl || ' ' || v_colrec.column_name || ' ';- END IF;-- -- Issue#23: Handle autogenerated columns and rewrite as a simpler IF THEN ELSE branch instead of a much more complex embedded CASE STATEMENT- IF v_colrec.is_generated = 'ALWAYS' and v_colrec.generation_expression IS NOT NULL THEN- -- searchable tsvector GENERATED ALWAYS AS (to_tsvector('simple'::regconfig, COALESCE(translate(email, '@.-'::citext, ' '::text), ''::text)) ) STORED- v_temp = v_colrec.data_type || ' GENERATED ALWAYS AS (' || v_colrec.generation_expression || ') STORED ';- ELSEIF v_colrec.udt_name in ('geometry', 'box2d', 'box2df', 'box3d', 'geography', 'geometry_dump', 'gidx', 'spheroid', 'valid_detail') THEN- v_temp = v_colrec.udt_name;- ELSEIF v_colrec.data_type = 'USER-DEFINED' THEN- v_temp = v_colrec.udt_schema || '.' || v_colrec.udt_name;- ELSEIF v_colrec.data_type = 'ARRAY' THEN- -- Issue#6 fix: handle arrays- v_temp = pg_temp.pg_get_coldef(in_schema, in_table,v_colrec.column_name);- -- v17 fix: handle case-sensitive for pg_get_serial_sequence that requires SQL Identifier handling- -- WHEN pg_get_serial_sequence(v_qualified, v_colrec.column_name) IS NOT NULL- ELSEIF pg_get_serial_sequence(quote_ident(in_schema) || '.' || quote_ident(in_table), v_colrec.column_name) IS NOT NULL THEN- -- Issue#8 fix: handle serial. Note: NOT NULL is implied so no need to declare it explicitly- v_temp = pg_temp.pg_get_coldef(in_schema, in_table,v_colrec.column_name);- ELSE- v_temp = v_colrec.data_type;- END IF;- -- RAISE NOTICE 'column def1=%', v_temp;-- -- handle IDENTITY columns- IF v_colrec.is_identity = 'YES' THEN- IF v_colrec.identity_generation = 'ALWAYS' THEN- v_temp = v_temp || ' GENERATED ALWAYS AS IDENTITY';- ELSE- v_temp = v_temp || ' GENERATED BY DEFAULT AS IDENTITY';- END IF;- ELSEIF v_colrec.character_maximum_length IS NOT NULL THEN- v_temp = v_temp || ('(' || v_colrec.character_maximum_length || ')');- ELSEIF v_colrec.numeric_precision > 0 AND v_colrec.numeric_scale > 0 THEN- v_temp = v_temp || '(' || v_colrec.numeric_precision || ',' || v_colrec.numeric_scale || ')';- END IF;-- -- Handle NULL/NOT NULL- IF bSerial THEN- v_temp = v_temp || ' NOT NULL';- ELSEIF v_colrec.is_nullable = 'NO' THEN- v_temp = v_temp || ' NOT NULL';- ELSEIF v_colrec.is_nullable = 'YES' THEN- v_temp = v_temp || ' NULL';- END IF;-- -- Handle defaults- IF v_colrec.column_default IS NOT null AND NOT bSerial THEN- -- RAISE NOTICE 'Setting default for column, %', v_colrec.column_name;- v_temp = v_temp || (' DEFAULT ' || v_colrec.column_default);- END IF;- v_temp = v_temp || ',' || E'\\n';- -- RAISE NOTICE 'column def2=%', v_temp;- v_table_ddl := v_table_ddl || v_temp;- -- RAISE NOTICE 'tabledef=%', v_table_ddl;-- END LOOP;- END IF;- IF bVerbose THEN RAISE NOTICE '(2)tabledef so far: %', v_table_ddl; END IF;-- -- define all the constraints: conparentid does not exist pre PGv11- IF v_pgversion < 110000 THEN- FOR v_constraintrec IN- SELECT con.conname as constraint_name, con.contype as constraint_type,- CASE- WHEN con.contype = 'p' THEN 1 -- primary key constraint- WHEN con.contype = 'u' THEN 2 -- unique constraint- WHEN con.contype = 'f' THEN 3 -- foreign key constraint- WHEN con.contype = 'c' THEN 4- ELSE 5- END as type_rank,- pg_get_constraintdef(con.oid) as constraint_definition- FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace- WHERE nsp.nspname = in_schema AND rel.relname = in_table ORDER BY type_rank- LOOP- v_constraint_name := v_constraintrec.constraint_name;- v_constraint_def := v_constraintrec.constraint_definition;- IF v_constraintrec.type_rank = 1 THEN- IF pkcnt = 0 OR pktype = 'PKEY_INTERNAL' THEN- -- internal def- v_constraint_name := v_constraintrec.constraint_name;- v_constraint_def := v_constraintrec.constraint_definition;- v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column- || 'CONSTRAINT' || ' '- || v_constraint_name || ' '- || v_constraint_def- || ',' || E'\\n';- ELSE- -- Issue#16 handle external PG def- SELECT 'ALTER TABLE ONLY ' || in_schema || '.' || c.relname || ' ADD CONSTRAINT ' || r.conname || ' ' || pg_catalog.pg_get_constraintdef(r.oid, true) || ';' INTO v_pkey_def- FROM pg_catalog.pg_constraint r, pg_class c, pg_namespace n where r.conrelid = c.oid and r.contype = 'p' and n.oid = r.connamespace and n.nspname = in_schema AND c.relname = in_table and r.conname = v_constraint_name;- END IF;- IF bPartition THEN- continue;- END IF;- ELSIF v_constraintrec.type_rank = 3 THEN- -- handle foreign key constraints- --Issue#22 fix: added FKEY_NONE check- IF fktype = 'FKEYS_NONE' THEN- -- skip- continue;- ELSIF fkcnt = 0 OR fktype = 'FKEYS_INTERNAL' THEN- -- internal def- v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column- || 'CONSTRAINT' || ' '- || v_constraint_name || ' '- || v_constraint_def- || ',' || E'\\n';- ELSE- -- external def- SELECT 'ALTER TABLE ONLY ' || n.nspname || '.' || c2.relname || ' ADD CONSTRAINT ' || r.conname || ' ' || pg_catalog.pg_get_constraintdef(r.oid, true) || ';' INTO v_fkey_def- FROM pg_constraint r, pg_class c1, pg_namespace n, pg_class c2 where r.conrelid = c1.oid and r.contype = 'f' and n.nspname = in_schema and n.oid = r.connamespace and r.conrelid = c2.oid and c2.relname = in_table;- v_fkey_defs = v_fkey_defs || v_fkey_def || E'\\n';- END IF;- ELSE- -- handle all other constraints besides PKEY and FKEYS as internal defs by default- v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column- || 'CONSTRAINT' || ' '- || v_constraint_name || ' '- || v_constraint_def- || ',' || E'\\n';- END IF;- if bVerbose THEN RAISE NOTICE 'DEBUG4: constraint name=% constraint_def=%', v_constraint_name,v_constraint_def; END IF;- constraintarr := constraintarr || v_constraintrec.constraint_name:: text;-- END LOOP;- ELSE- -- handle PG versions 11 and up- -- Issue#20: Fix logic for external PKEY and FKEYS- FOR v_constraintrec IN- SELECT con.conname as constraint_name, con.contype as constraint_type,- CASE- WHEN con.contype = 'p' THEN 1 -- primary key constraint- WHEN con.contype = 'u' THEN 2 -- unique constraint- WHEN con.contype = 'f' THEN 3 -- foreign key constraint- WHEN con.contype = 'c' THEN 4- ELSE 5- END as type_rank,- pg_get_constraintdef(con.oid) as constraint_definition- FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace- WHERE nsp.nspname = in_schema AND rel.relname = in_table- --Issue#13 added this condition:- AND con.conparentid = 0- ORDER BY type_rank- LOOP- v_constraint_name := v_constraintrec.constraint_name;- v_constraint_def := v_constraintrec.constraint_definition;- IF v_constraintrec.type_rank = 1 THEN- IF pkcnt = 0 OR pktype = 'PKEY_INTERNAL' THEN- -- internal def- v_constraint_name := v_constraintrec.constraint_name;- v_constraint_def := v_constraintrec.constraint_definition;- v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column- || 'CONSTRAINT' || ' '- || v_constraint_name || ' '- || v_constraint_def- || ',' || E'\\n';- ELSE- -- Issue#16 handle external PG def- SELECT 'ALTER TABLE ONLY ' || in_schema || '.' || c.relname || ' ADD CONSTRAINT ' || r.conname || ' ' || pg_catalog.pg_get_constraintdef(r.oid, true) || ';' INTO v_pkey_def- FROM pg_catalog.pg_constraint r, pg_class c, pg_namespace n where r.conrelid = c.oid and r.contype = 'p' and n.oid = r.connamespace and n.nspname = in_schema AND c.relname = in_table;- END IF;- IF bPartition THEN- continue;- END IF;- ELSIF v_constraintrec.type_rank = 3 THEN- -- handle foreign key constraints- --Issue#22 fix: added FKEY_NONE check- IF fktype = 'FKEYS_NONE' THEN- -- skip- continue;- ELSIF fkcnt = 0 OR fktype = 'FKEYS_INTERNAL' THEN- -- internal def- v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column- || 'CONSTRAINT' || ' '- || v_constraint_name || ' '- || v_constraint_def- || ',' || E'\\n';- ELSE- -- external def- SELECT 'ALTER TABLE ONLY ' || n.nspname || '.' || c2.relname || ' ADD CONSTRAINT ' || r.conname || ' ' || pg_catalog.pg_get_constraintdef(r.oid, true) || ';' INTO v_fkey_def- FROM pg_constraint r, pg_class c1, pg_namespace n, pg_class c2 where r.conrelid = c1.oid and r.contype = 'f' and n.nspname = in_schema and n.oid = r.connamespace and r.conrelid = c2.oid and c2.relname = in_table and- r.conname = v_constraint_name and r.conparentid = 0;- v_fkey_defs = v_fkey_defs || v_fkey_def || E'\\n';- END IF;- ELSE- -- handle all other constraints besides PKEY and FKEYS as internal defs by default- v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column- || 'CONSTRAINT' || ' '- || v_constraint_name || ' '- || v_constraint_def- || ',' || E'\\n';- END IF;- if bVerbose THEN RAISE NOTICE 'DEBUG4: constraint name=% constraint_def=%', v_constraint_name,v_constraint_def; END IF;- constraintarr := constraintarr || v_constraintrec.constraint_name:: text;-- END LOOP;- END IF;-- -- drop the last comma before ending the create statement, which should be right before the carriage return character- -- Issue#24: make sure the comma is there before removing it- select substring(v_table_ddl, length(v_table_ddl) - 1, 1) INTO v_temp;- IF v_temp = ',' THEN- v_table_ddl = substr(v_table_ddl, 0, length(v_table_ddl) - 1) || E'\\n';- END IF;- IF bVerbose THEN RAISE NOTICE '(3)tabledef so far: %', trim(v_table_ddl); END IF;-- -- ---------------------------------------------------------------------------- -- at this point we have everything up to the last table-enclosing parenthesis- -- ---------------------------------------------------------------------------- IF bVerbose THEN RAISE NOTICE '(4)tabledef so far: %', v_table_ddl; END IF;-- -- See if this is an inheritance-based child table and finish up the table create.- IF bPartition and bInheritance THEN- -- Issue#11: handle parent schema- -- v_table_ddl := v_table_ddl || ') INHERITS (' || in_schema || '.' || v_parent || ') ' || E'\\n' || v_relopts || ' ' || v_tablespace || ';' || E'\\n';- IF v_parent_schema = '' OR v_parent_schema IS NULL THEN v_parent_schema = in_schema; END IF;- v_table_ddl := v_table_ddl || ') INHERITS (' || v_parent_schema || '.' || v_parent || ') ' || E'\\n' || v_relopts || ' ' || v_tablespace || ';' || E'\\n';- END IF;-- IF v_pgversion >= 100000 AND NOT bPartition and NOT bInheritance THEN- -- See if this is a partitioned table (pg_class.relkind = 'p') and add the partitioned key- SELECT pg_get_partkeydef(c1.oid) as partition_key INTO v_partition_key FROM pg_class c1 JOIN pg_namespace n ON (n.oid = c1.relnamespace) LEFT JOIN pg_partitioned_table p ON (c1.oid = p.partrelid)- WHERE n.nspname = in_schema and n.oid = c1.relnamespace and c1.relname = in_table and c1.relkind = 'p';-- IF v_partition_key IS NOT NULL AND v_partition_key <> '' THEN- -- add partition clause- -- NOTE: cannot specify default tablespace for partitioned relations- -- v_table_ddl := v_table_ddl || ') PARTITION BY ' || v_partition_key || ' ' || v_tablespace || ';' || E'\\n';- v_table_ddl := v_table_ddl || ') PARTITION BY ' || v_partition_key || ';' || E'\\n';- ELSEIF v_relopts <> '' THEN- v_table_ddl := v_table_ddl || ') ' || v_relopts || ' ' || v_tablespace || ';' || E'\\n';- ELSE- -- end the create definition- v_table_ddl := v_table_ddl || ') ' || v_tablespace || ';' || E'\\n';- END IF;- END IF;-- IF bVerbose THEN RAISE NOTICE '(5)tabledef so far: %', v_table_ddl; END IF;-- -- Add closing paren for regular tables- -- IF NOT bPartition THEN- -- v_table_ddl := v_table_ddl || ') ' || v_relopts || ' ' || v_tablespace || E';\\n';- -- END IF;- -- RAISE NOTICE 'ddlsofar3: %', v_table_ddl;-- -- Issue#16 create the external PKEY def if indicated- IF v_pkey_def <> '' THEN- v_table_ddl := v_table_ddl || v_pkey_def || E'\\n';- END IF;-- -- Issue#20- IF v_fkey_defs <> '' THEN- v_table_ddl := v_table_ddl || v_fkey_defs || E'\\n';- END IF;-- IF bVerbose THEN RAISE NOTICE '(6)tabledef so far: %', v_table_ddl; END IF;-- -- create indexes- FOR v_indexrec IN- SELECT indexdef, COALESCE(tablespace, 'pg_default') as tablespace, indexname FROM pg_indexes WHERE (schemaname, tablename) = (in_schema, in_table)- LOOP- -- RAISE NOTICE 'DEBUG6: indexname=% indexdef=%', v_indexrec.indexname, v_indexrec.indexdef;- -- loop through constraints and skip ones already defined- bSkip = False;- FOREACH constraintelement IN ARRAY constraintarr- LOOP- IF constraintelement = v_indexrec.indexname THEN- -- RAISE NOTICE 'DEBUG7: skipping index, %', v_indexrec.indexname;- bSkip = True;- EXIT;- END IF;- END LOOP;- if bSkip THEN CONTINUE; END IF;-- -- Add IF NOT EXISTS clause so partition index additions will not be created if declarative partition in effect and index already created on parent- v_indexrec.indexdef := REPLACE(v_indexrec.indexdef, 'CREATE INDEX', 'CREATE INDEX IF NOT EXISTS');- -- Fix Issue#26: do it for unique/primary key indexes as well- v_indexrec.indexdef := REPLACE(v_indexrec.indexdef, 'CREATE UNIQUE INDEX', 'CREATE UNIQUE INDEX IF NOT EXISTS');- -- RAISE NOTICE 'DEBUG8: adding index, %', v_indexrec.indexname;-- -- NOTE: cannot specify default tablespace for partitioned relations- IF v_partition_key IS NOT NULL AND v_partition_key <> '' THEN- v_table_ddl := v_table_ddl || v_indexrec.indexdef || ';' || E'\\n';- ELSE- -- Issue#25: see if partial index or not- select CASE WHEN i.indpred IS NOT NULL THEN True ELSE False END INTO v_partial- FROM pg_index i JOIN pg_class c1 ON (i.indexrelid = c1.oid) JOIN pg_class c2 ON (i.indrelid = c2.oid)- WHERE c1.relnamespace::regnamespace::text = in_schema AND c2.relnamespace::regnamespace::text = in_schema AND c2.relname = in_table AND c1.relname = v_indexrec.indexname;- IF v_partial THEN- -- Put tablespace def before WHERE CLAUSE- v_temp = v_indexrec.indexdef;- v_pos = POSITION(' WHERE ' IN v_temp);- v_temp2 = SUBSTRING(v_temp, v_pos);- v_temp = SUBSTRING(v_temp, 1, v_pos);- v_table_ddl := v_table_ddl || v_temp || ' TABLESPACE ' || v_indexrec.tablespace || v_temp2 || ';' || E'\\n';- ELSE- v_table_ddl := v_table_ddl || v_indexrec.indexdef || ' TABLESPACE ' || v_indexrec.tablespace || ';' || E'\\n';- END IF;- END IF;-- END LOOP;- IF bVerbose THEN RAISE NOTICE '(7)tabledef so far: %', v_table_ddl; END IF;-- -- Issue#20: added logic for table and column comments- IF cmtcnt > 0 THEN- FOR v_rec IN- SELECT c.relname, 'COMMENT ON ' || CASE WHEN c.relkind in ('r','p') AND a.attname IS NULL THEN 'TABLE ' WHEN c.relkind in ('r','p') AND a.attname IS NOT NULL THEN 'COLUMN ' WHEN c.relkind = 'f' THEN 'FOREIGN TABLE '- WHEN c.relkind = 'm' THEN 'MATERIALIZED VIEW ' WHEN c.relkind = 'v' THEN 'VIEW ' WHEN c.relkind = 'i' THEN 'INDEX ' WHEN c.relkind = 'S' THEN 'SEQUENCE ' ELSE 'XX' END || n.nspname || '.' ||- CASE WHEN c.relkind in ('r','p') AND a.attname IS NOT NULL THEN quote_ident(c.relname) || '.' || a.attname ELSE quote_ident(c.relname) END || ' IS ' || quote_literal(d.description) || ';' as ddl- FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace) LEFT JOIN pg_description d ON (c.oid = d.objoid) LEFT JOIN pg_attribute a ON (c.oid = a.attrelid AND a.attnum > 0 and a.attnum = d.objsubid)- WHERE d.description IS NOT NULL AND n.nspname = in_schema AND c.relname = in_table ORDER BY 2 desc, ddl- LOOP- --RAISE NOTICE 'comments:%', v_rec.ddl;- v_table_ddl = v_table_ddl || v_rec.ddl || E'\\n';- END LOOP;- END IF;- IF bVerbose THEN RAISE NOTICE '(8)tabledef so far: %', v_table_ddl; END IF;-- IF trigtype = 'INCLUDE_TRIGGERS' THEN- -- Issue#14: handle multiple triggers for a table- FOR v_trigrec IN- select pg_get_triggerdef(t.oid, True) || ';' as triggerdef FROM pg_trigger t, pg_class c, pg_namespace n- WHERE n.nspname = in_schema and n.oid = c.relnamespace and c.relname = in_table and c.relkind = 'r' and t.tgrelid = c.oid and NOT t.tgisinternal- LOOP- v_table_ddl := v_table_ddl || v_trigrec.triggerdef;- v_table_ddl := v_table_ddl || E'\\n';- IF bVerbose THEN RAISE NOTICE 'triggerdef = %', v_trigrec.triggerdef; END IF;- END LOOP;- END IF;-- IF bVerbose THEN RAISE NOTICE '(9)tabledef so far: %', v_table_ddl; END IF;- -- add empty line- v_table_ddl := v_table_ddl || E'\\n';- IF bVerbose THEN RAISE NOTICE '(10)tabledef so far: %', v_table_ddl; END IF;-- -- reset search_path back to what it was- IF search_path_old = '' THEN- SELECT set_config('search_path', '', false) into v_temp;- ELSE- EXECUTE 'SET search_path = ' || search_path_old;- END IF;-- RETURN v_table_ddl;-- EXCEPTION- WHEN others THEN- BEGIN- GET STACKED DIAGNOSTICS v_diag1 = MESSAGE_TEXT, v_diag2 = PG_EXCEPTION_DETAIL, v_diag3 = PG_EXCEPTION_HINT, v_diag4 = RETURNED_SQLSTATE, v_diag5 = PG_CONTEXT, v_diag6 = PG_EXCEPTION_CONTEXT;- -- v_ret := 'line=' || v_diag6 || '. '|| v_diag4 || '. ' || v_diag1 || ' .' || v_diag2 || ' .' || v_diag3;- v_ret := 'line=' || v_diag6 || '. '|| v_diag4 || '. ' || v_diag1;- RAISE EXCEPTION '%', v_ret;- -- put additional coding here if necessarY- RETURN '';- END;-- END;- $$;`--const SCOPED_PG_GET_TABLEDEF_SQL: SafeSqlFragment = safeSql`+/** pg_temp.pg_get_tabledef: OID-scoped catalog lookups (no information_schema scans). */+const PG_GET_TABLEDEF_SQL: SafeSqlFragment = safeSql`DROP TYPE IF EXISTS pg_temp.tabledefs CASCADE;CREATE TYPE pg_temp.tabledefs AS ENUM ('PKEY_INTERNAL','PKEY_EXTERNAL','FKEYS_INTERNAL', 'FKEYS_EXTERNAL', 'COMMENTS', 'FKEYS_NONE', 'INCLUDE_TRIGGERS', 'NO_TRIGGERS');@@ -1434,20 +724,11 @@ const SCOPED_PG_GET_TABLEDEF_SQL: SafeSqlFragment = safeSql`END;$$;`-export const createPgGetTabledefSql = ({- scoped = false,-}: { scoped?: boolean } = {}): SafeSqlFragment =>- scoped ? SCOPED_PG_GET_TABLEDEF_SQL : LEGACY_PG_GET_TABLEDEF_SQL+export const createPgGetTabledefSql = (): SafeSqlFragment => PG_GET_TABLEDEF_SQL-export const getTableDefinitionSql = ({- id,- scoped = false,-}: {- id: number- scoped?: boolean-}): SafeSqlFragment => {+export const getTableDefinitionSql = ({ id }: { id: number }): SafeSqlFragment => {const sql = safeSql`- ${createPgGetTabledefSql({ scoped })}+ ${createPgGetTabledefSql()}with table_info as (select@@ -1473,14 +754,12 @@ export const getTableDefinitionSql = ({export const getEntityDefinitionsSql = ({schemas,limit = 100,- scoped = false,}: {schemas: string[]limit?: number- scoped?: boolean}): SafeSqlFragment => {const sql = safeSql`-${createPgGetTabledefSql({ scoped })}+${createPgGetTabledefSql()}with records as (selectdiff --git a/packages/pg-meta/src/sql/studio/table-editor/table.ts b/packages/pg-meta/src/sql/studio/table-editor/table.tsindex 32513011dd4..668416cfaf8 100644--- a/packages/pg-meta/src/sql/studio/table-editor/table.ts+++ b/packages/pg-meta/src/sql/studio/table-editor/table.ts@@ -31,17 +31,10 @@ export const getDuplicateRowsSQL = ({return safeSql`INSERT INTO ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} SELECT * FROM ${ident(sourceTableSchema)}.${ident(sourceTableName)};`}-export const getTableEditorSql = ({- id,- scoped = false,-}: {- id?: number- scoped?: boolean-}): SafeSqlFragment => {+export const getTableEditorSql = ({ id }: { id?: number }): SafeSqlFragment => {if (!id) return safeSql``- return scoped- ? safeSql`+ return safeSql`with base_table_info as (selectc.oid::int8 as id,@@ -344,304 +337,4 @@ export const getTableEditorSql = ({left join unique_indexes ui on b.id = ui.table_idleft join columns c on b.id = c.table_id;`- : safeSql`- -- FROZEN legacy path (pgMetaScopedIntrospection off): do not edit -- it must- -- keep matching production behavior until the flag cleanup deletes it.- 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 = ${literal(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', coalesce(bt.typname, t.typname),- 'format_schema', coalesce(nbt.nspname, nt.nspname),- '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/packages/pg-meta/src/sql/table-privileges.ts b/packages/pg-meta/src/sql/table-privileges.tsindex fcf8d789af2..fd8ccb44b19 100644--- a/packages/pg-meta/src/sql/table-privileges.ts+++ b/packages/pg-meta/src/sql/table-privileges.ts@@ -1,95 +1,9 @@import { safeSql, type SafeSqlFragment } from '../pg-format'-export const TABLE_PRIVILEGES_SQL = /* SQL */ safeSql`--- FROZEN legacy path: served while the pgMetaScopedIntrospection flag is off.--- Do not edit -- it must keep matching production behavior until the flag--- cleanup deletes it. getScopedTablePrivilegesSql is the replacement.------ Despite the name \`table_privileges\`, this includes other kinds of relations:--- views, matviews, etc. "Relation privileges" just doesn't roll off the tongue.------ For each relation, get its relacl in a jsonb format,--- e.g.------ '{postgres=arwdDxt/postgres}'------ becomes------ [--- {--- "grantee": "postgres",--- "grantor": "postgres",--- "is_grantable": false,--- "privilege_type": "INSERT"--- },--- ...--- ]-select- c.oid as relation_id,- nc.nspname as schema,- c.relname as name,- case- when c.relkind = 'r' then 'table'- when c.relkind = 'v' then 'view'- when c.relkind = 'm' then 'materialized_view'- when c.relkind = 'f' then 'foreign_table'- when c.relkind = 'p' then 'partitioned_table'- end as kind,- coalesce(- jsonb_agg(- jsonb_build_object(- 'grantor', grantor.rolname,- 'grantee', grantee.rolname,- 'privilege_type', _priv.privilege_type,- 'is_grantable', _priv.is_grantable- )- ) filter (where _priv is not null),- '[]'- ) as privileges-from pg_class c-join pg_namespace as nc- on nc.oid = c.relnamespace-left join lateral (- select grantor, grantee, privilege_type, is_grantable- from aclexplode(coalesce(c.relacl, acldefault('r', c.relowner)))-) as _priv on true-left join pg_roles as grantor- on grantor.oid = _priv.grantor-left join (- select- pg_roles.oid,- pg_roles.rolname- from pg_roles- union all- select- (0)::oid as oid, 'PUBLIC'-) as grantee (oid, rolname)- on grantee.oid = _priv.grantee-where c.relkind in ('r', 'v', 'm', 'f', 'p')- and not pg_is_other_temp_schema(c.relnamespace)- and (- pg_has_role(c.relowner, 'USAGE')- or has_table_privilege(- c.oid,- 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'- || case when current_setting('server_version_num')::int4 >= 170000 then ', MAINTAIN' else '' end- )- or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')- )-group by- c.oid,- nc.nspname,- c.relname,- c.relkind-`-/**- * Scoped variant of {@link TABLE_PRIVILEGES_SQL}: injects the wrapper's- * predicate into the base WHERE (before the aclexplode lateral / GROUP BY) so- * pg_class is pruned first, instead of scanning all relations then filtering.- * `scopeFilter` must be a `safeSql` fragment starting with `and ` (or empty)- * referencing base aliases `c` (pg_class) and `nc` (pg_namespace). Kept as a- * standalone template so the legacy constant stays byte-identical; rows match.+ * Relation ACLs (tables, views, matviews, foreign/partitioned). `scopeFilter`+ * is a `safeSql` fragment starting with `and ` (or empty) on aliases `c`+ * (pg_class) and `nc` (pg_namespace), applied before aclexplode / GROUP BY.*/export const getScopedTablePrivilegesSql = (scopeFilter: SafeSqlFragment = safeSql``diff --git a/packages/pg-meta/src/sql/tables.ts b/packages/pg-meta/src/sql/tables.tsindex f30796135db..23bd4b938da 100644--- a/packages/pg-meta/src/sql/tables.ts+++ b/packages/pg-meta/src/sql/tables.ts@@ -14,11 +14,7 @@ import { safeSql, type SafeSqlFragment } from '../pg-format'* relationships filter keeps BOTH directions (conrelid OR confrelid), matching* the outgoing/incoming FK rows the unscoped query would have matched by name.*- * When `targetOid` is omitted the injected fragments are empty and the rendered- * SQL is the full-catalog query used by existing consumers. Shared correctness- * fixes belong in this builder so scoped and unscoped consumers stay- * behaviorally equivalent; execution-based tests in test/tables.test.ts enforce- * that equivalence.+ * Omit `targetOid` for the full-catalog listing used by `tables.list`.*/export const getTablesSql = (targetOid?: SafeSqlFragment) => {const mainScope = targetOid@@ -33,10 +29,9 @@ export const getTablesSql = (targetOid?: SafeSqlFragment) => {? safeSql`and (c.conrelid = ${targetOid} or c.confrelid = ${targetOid})`: safeSql``- // Scoped path only: deterministic relationships order (plan-order dependent+ // retrieve only: deterministic relationships order (plan-order dependent// otherwise). A composite FK expands to one entry per ordinal column pair- // sharing constraint_name, so tie-break on the column names. Empty for- // unscoped consumers, preserving their existing plan-dependent order.+ // sharing constraint_name, so tie-break on the column names.const relOrder = targetOid? safeSql` order by relationships.constraint_name, relationships.source_column_name, relationships.target_column_name`: safeSql``@@ -141,7 +136,4 @@ group by`}-// Unscoped full-catalog rendering served while the pgMetaScopedIntrospection-// flag is off. Scope-specific changes belong behind targetOid; shared-// correctness fixes apply to both this path and scoped tables.retrieve.export const TABLES_SQL = getTablesSql()diff --git a/packages/pg-meta/src/sql/types.ts b/packages/pg-meta/src/sql/types.tsindex d33c31c79ba..356315ccf2a 100644--- a/packages/pg-meta/src/sql/types.ts+++ b/packages/pg-meta/src/sql/types.ts@@ -1,68 +1,12 @@import { safeSql } from '../pg-format'/**- * User-defined types introspection. TYPES_SQL (legacy, FROZEN below) left-joins- * two catalog-wide GROUP BY aggregates (slow on a large catalog). SCOPED_TYPES_SQL- * (opt-in) returns identical rows but computes enums/attrs per surviving row via- * correlated index-scan subqueries after the schema/array filters. Both end at- * the same trailing WHERE so pg-meta-types.ts#list appends the same filter/limit- * fragments (and, scoped-only, ORDER BY t.oid) to either. Equivalence is proven- * by execution tests in test/types.test.ts, not a byte snapshot.+ * User-defined types. Enums/attrs are correlated subqueries after schema+ * filters so the planner does not GROUP BY the whole catalog first.+ * Ends at a trailing WHERE so pg-meta-types.ts#list can append filters,+ * `order by t.oid`, and limit.*/export const TYPES_SQL = /* SQL */ safeSql`--- FROZEN legacy path: served while the pgMetaScopedIntrospection flag is off.--- Do not edit -- it must keep matching production behavior until the flag--- cleanup deletes it. SCOPED_TYPES_SQL is the replacement.-select- t.oid::int8 as id,- t.typname as name,- n.nspname as schema,- format_type (t.oid, null) as format,- coalesce(t_enums.enums, '[]') as enums,- coalesce(t_attributes.attributes, '[]') as attributes,- obj_description (t.oid, 'pg_type') as comment-from- pg_type t- left join pg_namespace n on n.oid = t.typnamespace- left join (- select- enumtypid,- jsonb_agg(enumlabel order by enumsortorder) as enums- from- pg_enum- group by- enumtypid- ) as t_enums on t_enums.enumtypid = t.oid- left join (- select- oid,- jsonb_agg(- jsonb_build_object('name', a.attname, 'type_id', a.atttypid::int8)- order by a.attnum asc- ) as attributes- from- pg_class c- join pg_attribute a on a.attrelid = c.oid- where- c.relkind = 'c' and not a.attisdropped- group by- c.oid- ) as t_attributes on t_attributes.oid = t.typrelid-where- (- t.typrelid = 0- or (- select- c.relkind = 'c'- from- pg_class c- where- c.oid = t.typrelid- )- )-`--export const SCOPED_TYPES_SQL = /* SQL */ safeSql`selectt.oid::int8 as id,t.typname as name,diff --git a/packages/pg-meta/test/column-privileges.test.ts b/packages/pg-meta/test/column-privileges.test.tsindex a089a62bad0..6a76e49ff64 100644--- a/packages/pg-meta/test/column-privileges.test.ts+++ b/packages/pg-meta/test/column-privileges.test.ts@@ -100,6 +100,7 @@ withTestDatabase('revoke & grant column privileges', async ({ executeQuery }) =>let privs = listZod.parse(await executeQuery(listSqlTodos))expect(privs.length).toBe(1)+ privs[0].privileges.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))expect(privs[0]).toMatchInlineSnapshot({ column_id: expect.stringMatching(/^\d+\.\d+$/) },`@@ -108,28 +109,22 @@ withTestDatabase('revoke & grant column privileges', async ({ executeQuery }) =>"column_name": "id","privileges": [{- "grantee": "${testRole}",- "grantor": "postgres",- "is_grantable": false,- "privilege_type": "UPDATE",- },- {- "grantee": "${testRole}",+ "grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "SELECT",+ "privilege_type": "INSERT",},{- "grantee": "${testRole}",+ "grantee": "postgres","grantor": "postgres","is_grantable": false,"privilege_type": "REFERENCES",},{- "grantee": "${testRole}",+ "grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "INSERT",+ "privilege_type": "SELECT",},{"grantee": "postgres",@@ -138,22 +133,28 @@ withTestDatabase('revoke & grant column privileges', async ({ executeQuery }) =>"privilege_type": "UPDATE",},{- "grantee": "postgres",+ "grantee": "${testRole}","grantor": "postgres","is_grantable": false,- "privilege_type": "SELECT",+ "privilege_type": "INSERT",},{- "grantee": "postgres",+ "grantee": "${testRole}","grantor": "postgres","is_grantable": false,"privilege_type": "REFERENCES",},{- "grantee": "postgres",+ "grantee": "${testRole}","grantor": "postgres","is_grantable": false,- "privilege_type": "INSERT",+ "privilege_type": "SELECT",+ },+ {+ "grantee": "${testRole}",+ "grantor": "postgres",+ "is_grantable": false,+ "privilege_type": "UPDATE",},],"relation_name": "todos",@@ -175,6 +176,7 @@ withTestDatabase('revoke & grant column privileges', async ({ executeQuery }) =>// Verify privileges were revokedprivs = listZod.parse(await executeQuery(listSqlTodos))expect(privs.length).toBe(1)+ privs[0].privileges.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))expect(privs[0]).toMatchInlineSnapshot({ column_id: expect.stringMatching(/^\d+\.\d+$/) },`@@ -186,25 +188,25 @@ withTestDatabase('revoke & grant column privileges', async ({ executeQuery }) =>"grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "UPDATE",+ "privilege_type": "INSERT",},{"grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "SELECT",+ "privilege_type": "REFERENCES",},{"grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "REFERENCES",+ "privilege_type": "SELECT",},{"grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "INSERT",+ "privilege_type": "UPDATE",},],"relation_name": "todos",@@ -242,6 +244,7 @@ withTestDatabase(// Verify privileges were grantedlet privs = listZod.parse(await executeQuery(listSqlT1))expect(privs.length).toBe(1)+ privs[0].privileges.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))expect(privs[0]).toMatchInlineSnapshot({ column_id: expect.stringMatching(/^\d+\.\d+$/) },`@@ -250,28 +253,22 @@ withTestDatabase("column_name": "c 1","privileges": [{- "grantee": "${testRole}",- "grantor": "postgres",- "is_grantable": false,- "privilege_type": "UPDATE",- },- {- "grantee": "${testRole}",+ "grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "SELECT",+ "privilege_type": "INSERT",},{- "grantee": "${testRole}",+ "grantee": "postgres","grantor": "postgres","is_grantable": false,"privilege_type": "REFERENCES",},{- "grantee": "${testRole}",+ "grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "INSERT",+ "privilege_type": "SELECT",},{"grantee": "postgres",@@ -280,22 +277,28 @@ withTestDatabase("privilege_type": "UPDATE",},{- "grantee": "postgres",+ "grantee": "${testRole}","grantor": "postgres","is_grantable": false,- "privilege_type": "SELECT",+ "privilege_type": "INSERT",},{- "grantee": "postgres",+ "grantee": "${testRole}","grantor": "postgres","is_grantable": false,"privilege_type": "REFERENCES",},{- "grantee": "postgres",+ "grantee": "${testRole}","grantor": "postgres","is_grantable": false,- "privilege_type": "INSERT",+ "privilege_type": "SELECT",+ },+ {+ "grantee": "${testRole}",+ "grantor": "postgres",+ "is_grantable": false,+ "privilege_type": "UPDATE",},],"relation_name": "t 1",@@ -316,6 +319,7 @@ withTestDatabase(// Verify privileges were revokedprivs = listZod.parse(await executeQuery(listSqlT1))expect(privs.length).toBe(1)+ privs[0].privileges.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))expect(privs[0]).toMatchInlineSnapshot({ column_id: expect.stringMatching(/^\d+\.\d+$/) },`@@ -327,25 +331,25 @@ withTestDatabase("grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "UPDATE",+ "privilege_type": "INSERT",},{"grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "SELECT",+ "privilege_type": "REFERENCES",},{"grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "REFERENCES",+ "privilege_type": "SELECT",},{"grantee": "postgres","grantor": "postgres","is_grantable": false,- "privilege_type": "INSERT",+ "privilege_type": "UPDATE",},],"relation_name": "t 1",@@ -356,7 +360,7 @@ withTestDatabase(})-withTestDatabase('scoped list matches the legacy path row-for-row', async ({ executeQuery }) => {+withTestDatabase('list surfaces PUBLIC and column-level grants', async ({ executeQuery }) => {await executeQuery(`drop role if exists col_grantee_a;drop role if exists col_grantee_b;@@ -371,47 +375,9 @@ withTestDatabase('scoped list matches the legacy path row-for-row', async ({ exegrant select (id) on public.col_priv_view to col_grantee_b;`)- // Neither path orders rows or the privileges array (see the note on the first- // test in this file), and the two plans emit them in different orders, so- // compare on normalized copies.- const normalize = <T extends { column_id: string; privileges: Array<unknown> }>(rows: Array<T>) =>- rows- .map((row) => ({- ...row,- privileges: [...row.privileges].sort((a, b) =>- JSON.stringify(a).localeCompare(JSON.stringify(b))- ),- }))- .sort((a, b) => a.column_id.localeCompare(b.column_id))-- for (const options of [- {},- { includedSchemas: ['public'] },- { excludedSchemas: ['public'] },- { includedSchemas: ['public'], relationName: 'col_priv_demo' },- { includedSchemas: ['public'], relationName: 'col_priv_view' },- { includedSchemas: ['public'], relationName: 'does_not_exist' },- { includeSystemSchemas: true, includedSchemas: ['public'] },- ]) {- const legacy = pgMeta.columnPrivileges.list(options)- const scoped = pgMeta.columnPrivileges.list({ ...options, scoped: true })- const legacyRes = legacy.zod.parse(await executeQuery(legacy.sql))- const scopedRes = scoped.zod.parse(await executeQuery(scoped.sql))- expect(normalize(scopedRes), `list options: ${JSON.stringify(options)}`).toEqual(- normalize(legacyRes)- )- // Row counts must match exactly, independent of the normalization above.- expect(scopedRes.length, `row count for options: ${JSON.stringify(options)}`).toBe(- legacyRes.length- )- }-- // The scoped path must surface the PUBLIC grantee, and the column-level grants- // that only the second UNION arm can produce.const { sql, zod } = pgMeta.columnPrivileges.list({includedSchemas: ['public'],relationName: 'col_priv_demo',- scoped: true,})const rows = zod.parse(await executeQuery(sql))const dataColumn = rows.find((r) => r.column_name === 'data')!@@ -423,14 +389,16 @@ withTestDatabase('scoped list matches the legacy path row-for-row', async ({ exe)).toBe(true)- // columnIds: the scoped path prunes pg_class by relation oid and keeps the- // exact attnum predicate outside, so it must still match legacy exactly.const columnIds = rows.map((r) => r.column_id).slice(0, 2)- const legacyByIds = pgMeta.columnPrivileges.list({ columnIds })- const scopedByIds = pgMeta.columnPrivileges.list({ columnIds, scoped: true })- expect(normalize(scopedByIds.zod.parse(await executeQuery(scopedByIds.sql)))).toEqual(- normalize(legacyByIds.zod.parse(await executeQuery(legacyByIds.sql)))- )+ const byIds = pgMeta.columnPrivileges.list({ columnIds })+ const byIdsRows = byIds.zod.parse(await executeQuery(byIds.sql))+ expect(byIdsRows.map((r) => r.column_id).sort()).toEqual([...columnIds].sort())++ const missing = pgMeta.columnPrivileges.list({+ includedSchemas: ['public'],+ relationName: 'does_not_exist',+ })+ expect(missing.zod.parse(await executeQuery(missing.sql))).toEqual([])})const columnGrants = async (diff --git a/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts b/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.tsindex a1a7b8f1098..ddb4786bb4d 100644--- a/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts+++ b/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts@@ -31,17 +31,8 @@ import { cleanupRoot, createTestDatabase } from '../../db/utils'* unavoidable scans carrying a written justification (see test/db/plan-guard.ts* for THE RULE).*- * Context: a real production catalog had ~267K pg_class rows. Before- * https://github.com/supabase/supabase/pull/47894, unscoped CTEs in the Table- * Editor query full-scanned pg_index/pg_constraint on every open -- O(catalog)- * work regardless of which table was opened, taking 30-58s at incident scale.- *- * NOTE: the scoped introspection behavior from PR #47894 defaults to OFF and is- * gated behind a `scoped` flag so Studio can enable it progressively via a- * feature flag. The legacy (scoped:false) path is intentionally NOT exercised- * here -- this guard tests the SCOPED path, so every builder below is called- * with `scoped: true`. Once the rollout completes, drop the legacy path and the- * flag, and this guard becomes the only shape.+ * Unscoped CTEs here once full-scanned pg_index/pg_constraint on every Table+ * Editor open, so cost grew with the whole catalog instead of the opened table.*/let db: Awaited<ReturnType<typeof createTestDatabase>>@@ -86,18 +77,18 @@ const TABLE_EDITOR_BUDGET = {}test('getTableEditorSql: plan stays scoped for a mid-chain table (stress.t_1000)', async () => {- const result = await explainAnalyze(db, getTableEditorSql({ id: midChainTableId, scoped: true }))+ const result = await explainAnalyze(db, getTableEditorSql({ id: midChainTableId }))assertPlanWithinBudget(result, TABLE_EDITOR_BUDGET)}, 60_000)test('getTableEditorSql: plan stays scoped for the hub table with many incoming FKs (stress.t_0)', async () => {- const result = await explainAnalyze(db, getTableEditorSql({ id: hubTableId, scoped: true }))+ const result = await explainAnalyze(db, getTableEditorSql({ id: hubTableId }))assertPlanWithinBudget(result, TABLE_EDITOR_BUDGET)}, 60_000)test('getTableEditorSql: real (non-EXPLAIN) query returns a well-formed entity for t_1000', async () => {const [{ entity }] = await db.executeQuery<Array<{ entity: any }>>(- getTableEditorSql({ id: midChainTableId, scoped: true })+ getTableEditorSql({ id: midChainTableId }))expect(entity.schema).toBe('stress')@@ -253,7 +244,7 @@ test('getIndexesSQL: plan stays scoped for a schema', async () => {// setup on the (single, pooled) connection first, then EXPLAIN only the tail// SELECT -- which is the part whose plan we actually care about.async function explainDefinitionQuery(fullSql: string) {- const setup = createPgGetTabledefSql({ scoped: true }) as unknown as string+ const setup = createPgGetTabledefSql() as unknown as stringconst tail = fullSql.slice(fullSql.indexOf(setup) + setup.length)await db.executeQuery(setup)return explainAnalyze(db, tail)@@ -263,9 +254,7 @@ async function explainDefinitionQuery(fullSql: string) {// Only the outer table_info lookup is planned (pg_get_tabledef is an opaque// plpgsql function); it resolves the table by oid, so no scaling seq scans.test('getTableDefinitionSql: plan stays scoped for a single table', async () => {- const result = await explainDefinitionQuery(- getTableDefinitionSql({ id: midChainTableId, scoped: true })- )+ const result = await explainDefinitionQuery(getTableDefinitionSql({ id: midChainTableId }))assertPlanWithinBudget(result, {})}, 60_000)@@ -284,7 +273,7 @@ test('getTableDefinitionSql: plan stays scoped for a single table', async () =>// on a 12K-table catalog measured ~0.9s post-fix.test('getEntityDefinitionsSql: plan stays scoped for a schema', async () => {const result = await explainDefinitionQuery(- getEntityDefinitionsSql({ schemas: ['stress'], limit: 100, scoped: true })+ getEntityDefinitionsSql({ schemas: ['stress'], limit: 100 }))assertPlanWithinBudget(result, {// ~0.3s measured at 2000 tables post-fix for a 100-entity page; loose@@ -320,15 +309,12 @@ const TYPES_LIST_BUDGET = {},}test('types.list: scoped plan stays scoped for a schema', async () => {- const result = await explainAnalyze(- db,- types.list({ includedSchemas: ['stress'], scoped: true }).sql- )+ const result = await explainAnalyze(db, types.list({ includedSchemas: ['stress'] }).sql)assertPlanWithinBudget(result, TYPES_LIST_BUDGET)}, 60_000)test('types.list: scoped real query returns the schema’s enums and composites', async () => {- const { sql, zod } = types.list({ includedSchemas: ['stress'], scoped: true })+ const { sql, zod } = types.list({ includedSchemas: ['stress'] })const rows = zod.parse(await db.executeQuery(sql))// stress has enums (mood/priority/e_*) and composites (addr/pair/ct_*).const mood = rows.find((t) => t.name === 'mood')@@ -357,10 +343,7 @@ const TABLE_PRIVILEGES_BUDGET = {// Scoped pushes the schema filter into the base WHERE (before the aclexplode// lateral / GROUP BY) so pg_class is pruned before privileges are exploded.test('tablePrivileges.list: scoped plan stays scoped for a schema', async () => {- const result = await explainAnalyze(- db,- tablePrivileges.list({ includedSchemas: ['stress'], scoped: true }).sql- )+ const result = await explainAnalyze(db, tablePrivileges.list({ includedSchemas: ['stress'] }).sql)assertPlanWithinBudget(result, TABLE_PRIVILEGES_BUDGET)}, 60_000)@@ -370,7 +353,7 @@ test('tablePrivileges.list: scoped plan stays scoped for a schema', async () =>test('tablePrivileges.retrieve: scoped plan stays scoped for a single relation', async () => {const result = await explainAnalyze(db,- tablePrivileges.retrieve({ name: 't_1000', schema: 'stress', scoped: true }).sql+ tablePrivileges.retrieve({ name: 't_1000', schema: 'stress' }).sql)assertPlanWithinBudget(result, TABLE_PRIVILEGES_BUDGET)}, 60_000)@@ -402,7 +385,6 @@ test('columnPrivileges.list: scoped plan stays scoped for a single table', asynccolumnPrivileges.list({includedSchemas: ['stress'],relationName: 't_1000',- scoped: true,}).sql)assertPlanWithinBudget(result, COLUMN_PRIVILEGES_TABLE_SCOPED_BUDGET)@@ -426,7 +408,7 @@ const COLUMN_PRIVILEGES_SCHEMA_SCOPED_BUDGET = {test('columnPrivileges.list: scoped plan stays scoped for a schema', async () => {const result = await explainAnalyze(db,- columnPrivileges.list({ includedSchemas: ['stress'], scoped: true }).sql+ columnPrivileges.list({ includedSchemas: ['stress'] }).sql)assertPlanWithinBudget(result, COLUMN_PRIVILEGES_SCHEMA_SCOPED_BUDGET)}, 60_000)@@ -456,28 +438,22 @@ const TABLES_RETRIEVE_BUDGET = {}test('tables.retrieve: scoped plan stays scoped for a single table by id', async () => {- const result = await explainAnalyze(- db,- tables.retrieve({ id: midChainTableId, scoped: true }).sql- )+ const result = await explainAnalyze(db, tables.retrieve({ id: midChainTableId }).sql)assertPlanWithinBudget(result, TABLES_RETRIEVE_BUDGET)}, 60_000)test('tables.retrieve: scoped plan stays scoped for a single table by name+schema', async () => {- const result = await explainAnalyze(- db,- tables.retrieve({ name: 't_1000', schema: 'stress', scoped: true }).sql- )+ const result = await explainAnalyze(db, tables.retrieve({ name: 't_1000', schema: 'stress' }).sql)assertPlanWithinBudget(result, TABLES_RETRIEVE_BUDGET)}, 60_000)test('tables.retrieve: scoped plan stays scoped for a composite-FK hub', async () => {- const result = await explainAnalyze(db, tables.retrieve({ id: hubTableId, scoped: true }).sql)+ const result = await explainAnalyze(db, tables.retrieve({ id: hubTableId }).sql)assertPlanWithinBudget(result, TABLES_RETRIEVE_BUDGET)}, 60_000)test('tables.retrieve: composite FKs stay ordinally paired at stress scale', async () => {- const { sql, zod } = tables.retrieve({ id: midChainTableId, scoped: true })+ const { sql, zod } = tables.retrieve({ id: midChainTableId })const row = zod.parse((await db.executeQuery(sql))[0])const chainRelationships = row.relationships.filter(({ source_table_name, target_table_name }) =>diff --git a/packages/pg-meta/test/sql/studio/rows-count.test.ts b/packages/pg-meta/test/sql/studio/rows-count.test.tsindex 41d3bfcc975..76a67535475 100644--- a/packages/pg-meta/test/sql/studio/rows-count.test.ts+++ b/packages/pg-meta/test/sql/studio/rows-count.test.ts@@ -42,24 +42,12 @@ const runCount = async (db: Db, args: CountArgs) => {return { count: Number(row.count), is_estimate: row.is_estimate }}-// Execute BOTH the scoped and legacy renderings of the same args against the DB-// and assert identical results -- the equivalence contract for every case where-// the two paths must agree (the ONLY intentional divergence is a never-analyzed-// table whose heap exceeds the byte gate; that asymmetry is the fix and is-// asserted separately below).-const assertScopedEqualsLegacy = async (db: Db, base: Omit<CountArgs, 'scoped'>) => {- const legacy = await runCount(db, { ...base, scoped: false })- const scoped = await runCount(db, { ...base, scoped: true })- expect(scoped, 'scoped must equal legacy for this case').toEqual(legacy)- return scoped-}-// A never-analyzed table has pg_class.reltuples = -1 -- true for a brand-new// EMPTY table, a small one, AND a freshly bulk-loaded huge one. autovacuum is// disabled on every fixture so reltuples cannot flip mid-test.withTestDatabase(- 'scoped: empty never-analyzed table -> exact count 0, is_estimate=false (both modes)',+ 'empty never-analyzed table -> exact count 0 (writable and read-only)',async (db) => {await db.executeQuery(`create table public.empty_t (id int primary key) with (autovacuum_enabled = false);`@@ -70,8 +58,8 @@ withTestDatabase(// Postgres estimates a never-vacuumed heap at a ~10-page minimum, so a naive// reltuples=-1 -> estimate would report phantom rows here. The size gate// routes an empty (0-byte) heap to an exact count instead.- expect(await runCount(db, { table, scoped: true })).toEqual({ count: 0, is_estimate: false })- expect(await runCount(db, { table, scoped: true, isReadOnlyContext: true })).toEqual({+ expect(await runCount(db, { table })).toEqual({ count: 0, is_estimate: false })+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({count: 0,is_estimate: false,})@@ -79,7 +67,7 @@ withTestDatabase()withTestDatabase(- 'scoped: small never-analyzed table -> exact count, is_estimate=false (both modes)',+ 'small never-analyzed table -> exact count (writable and read-only)',async (db) => {await db.executeQuery(`create table public.small_unanalyzed (id int primary key, val text)@@ -90,56 +78,47 @@ withTestDatabase(const table = await tableOf(db, 'public.small_unanalyzed', 'small_unanalyzed', 'public')// Heap is a few tens of KB -- well under the byte gate -> exact count.- expect(await runCount(db, { table, scoped: true })).toEqual({ count: 1000, is_estimate: false })- expect(await runCount(db, { table, scoped: true, isReadOnlyContext: true })).toEqual({+ expect(await runCount(db, { table })).toEqual({ count: 1000, is_estimate: false })+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({count: 1000,is_estimate: false,})})-withTestDatabase(- 'scoped INTENTIONALLY diverges from legacy: large never-analyzed table -> estimate',- async (db) => {- // Wide rows (~300-byte payload) so the heap clears the ~10MB byte gate with a- // modest, fast-to-insert row count (~19MB at 60k rows) -- the case the legacy- // path mishandles (treats reltuples=-1 as small, runs a timing-out count).- await db.executeQuery(`+withTestDatabase('large never-analyzed table -> estimate', async (db) => {+ // Wide rows (~300-byte payload) so the heap clears the ~10MB byte gate with a+ // modest, fast-to-insert row count (~19MB at 60k rows) so reltuples=-1+ // would otherwise look "small" and exact-count.+ await db.executeQuery(`create table public.bulk_unanalyzed (id int primary key, val text)with (autovacuum_enabled = false);insert into public.bulk_unanalyzedselect g, repeat('x', 300) from generate_series(1, 60000) g;`)- expect(await reltuplesOf(db, 'public.bulk_unanalyzed')).toBe(-1)- const [{ bytes }] = await db.executeQuery<{ bytes: number }[]>(- `select pg_relation_size('public.bulk_unanalyzed'::regclass)::int8 as bytes;`- )- expect(Number(bytes)).toBeGreaterThan(10_000_000)- const table = await tableOf(db, 'public.bulk_unanalyzed', 'bulk_unanalyzed', 'public')-- // Non-readonly scoped: EXPLAIN-based estimate (works without ANALYZE).- const scoped = await runCount(db, { table, scoped: true })- expect(scoped.is_estimate).toBe(true)- expect(scoped.count).toBeGreaterThan(1000)- expect(scoped.count).not.toBe(-1)-- // Readonly scoped: cannot create the estimate function -> reports -1 as an- // estimate rather than a timing-out exact count.- expect(await runCount(db, { table, scoped: true, isReadOnlyContext: true })).toEqual({- count: -1,- is_estimate: true,- })-- // The intentional divergence: legacy (scoped:false) still runs an exact count- // on the -1 table (the pre-fix behavior the scoped path corrects).- const legacy = await runCount(db, { table })- expect(legacy).toEqual({ count: 60000, is_estimate: false })- expect(legacy.is_estimate).not.toBe(scoped.is_estimate)- }-)+ expect(await reltuplesOf(db, 'public.bulk_unanalyzed')).toBe(-1)+ const [{ bytes }] = await db.executeQuery<{ bytes: number }[]>(+ `select pg_relation_size('public.bulk_unanalyzed'::regclass)::int8 as bytes;`+ )+ expect(Number(bytes)).toBeGreaterThan(10_000_000)+ const table = await tableOf(db, 'public.bulk_unanalyzed', 'bulk_unanalyzed', 'public')++ // Writable: EXPLAIN-based estimate (works without ANALYZE).+ const writable = await runCount(db, { table })+ expect(writable.is_estimate).toBe(true)+ expect(writable.count).toBeGreaterThan(1000)+ expect(writable.count).not.toBe(-1)++ // Read-only cannot create the estimate function -> reports -1 as an+ // estimate rather than a timing-out exact count.+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({+ count: -1,+ is_estimate: true,+ })+})withTestDatabase(- 'scoped == legacy for an analyzed table below THRESHOLD_COUNT (default, filtered, enforceExactCount)',+ 'analyzed table below THRESHOLD_COUNT (default, filtered, enforceExactCount)',async (db) => {await db.executeQuery(`create table public.analyzed_small (id int primary key, status text);@@ -151,25 +130,25 @@ withTestDatabase(const table = await tableOf(db, 'public.analyzed_small', 'analyzed_small', 'public')const activeFilter: Filter[] = [{ column: 'status', operator: '=', value: 'active' }]- // Default count: both paths exact-count a small analyzed table.- expect(await assertScopedEqualsLegacy(db, { table })).toEqual({ count: 10, is_estimate: false })+ // Small analyzed table: exact count.+ expect(await runCount(db, { table })).toEqual({ count: 10, is_estimate: false })// Read-only default count agrees too.- expect(await assertScopedEqualsLegacy(db, { table, isReadOnlyContext: true })).toEqual({+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({count: 10,is_estimate: false,})// Filtered count agrees.- expect(await assertScopedEqualsLegacy(db, { table, filters: activeFilter })).toEqual({+ expect(await runCount(db, { table, filters: activeFilter })).toEqual({count: 5,is_estimate: false,})- // enforceExactCount ignores scoped entirely and agrees, with/without filters.- expect(await assertScopedEqualsLegacy(db, { table, enforceExactCount: true })).toEqual({+ // enforceExactCount always runs a real count, with or without filters.+ expect(await runCount(db, { table, enforceExactCount: true })).toEqual({count: 10,is_estimate: false,})expect(- await assertScopedEqualsLegacy(db, {+ await runCount(db, {table,enforceExactCount: true,filters: activeFilter,@@ -178,46 +157,40 @@ withTestDatabase(})-withTestDatabase(- 'scoped == legacy for an analyzed table over THRESHOLD_COUNT (estimate path unchanged)',- async (db) => {- // reltuples > 50000 after analyze routes BOTH paths to the estimate branch- // (raw reltuples when unfiltered) -- identical output; the byte gate only- // affects the reltuples = -1 case, not this one.- await db.executeQuery(`+withTestDatabase('analyzed table over THRESHOLD_COUNT uses estimate', async (db) => {+ // reltuples > 50000 after analyze uses the estimate branch (raw reltuples+ // when unfiltered). The byte gate only affects reltuples = -1.+ await db.executeQuery(`create table public.big_analyzed (id int primary key)with (autovacuum_enabled = false);insert into public.big_analyzed select generate_series(1, 60000);analyze public.big_analyzed;`)- expect(await reltuplesOf(db, 'public.big_analyzed')).toBeGreaterThan(50000)- const table = await tableOf(db, 'public.big_analyzed', 'big_analyzed', 'public')+ expect(await reltuplesOf(db, 'public.big_analyzed')).toBeGreaterThan(50000)+ const table = await tableOf(db, 'public.big_analyzed', 'big_analyzed', 'public')- // Non-readonly: both return the raw reltuples estimate.- const scoped = await assertScopedEqualsLegacy(db, { table })- expect(scoped.is_estimate).toBe(true)- expect(scoped.count).toBeGreaterThan(1000)+ const estimated = await runCount(db, { table })+ expect(estimated.is_estimate).toBe(true)+ expect(estimated.count).toBeGreaterThan(1000)- // Read-only: both report -1 as an estimate.- expect(await assertScopedEqualsLegacy(db, { table, isReadOnlyContext: true })).toEqual({- count: -1,- is_estimate: true,- })+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({+ count: -1,+ is_estimate: true,+ })- // enforceExactCount over the threshold still runs a real count in both paths.- expect(await assertScopedEqualsLegacy(db, { table, enforceExactCount: true })).toEqual({- count: 60000,- is_estimate: false,- })- }-)+ // enforceExactCount over the threshold still runs a real count.+ expect(await runCount(db, { table, enforceExactCount: true })).toEqual({+ count: 60000,+ is_estimate: false,+ })+})// A partitioned PARENT (relkind 'p') has no storage of its own, so// pg_relation_size(parent) is 0. The size gate must use the whole partition tree// or a large never-analyzed partitioned table would be misclassified as small// and exact-counted across all partitions -- the exact timeout being fixed.withTestDatabase(- 'scoped: large never-analyzed PARTITIONED table -> estimate (partition-tree size gate)',+ 'large never-analyzed PARTITIONED table -> estimate (partition-tree size gate)',async (db) => {await db.executeQuery(`create table public.part_big (id int, region text, val text) partition by list (region);@@ -241,23 +214,20 @@ withTestDatabase(expect(Number(tree)).toBeGreaterThan(10_000_000) // the tree sum clears the gateconst table = await tableOf(db, 'public.part_big', 'part_big', 'public')- const scoped = await runCount(db, { table, scoped: true })- expect(scoped.is_estimate).toBe(true)- expect(scoped.count).toBeGreaterThan(1000)- expect(scoped.count).not.toBe(-1)+ const estimated = await runCount(db, { table })+ expect(estimated.is_estimate).toBe(true)+ expect(estimated.count).toBeGreaterThan(1000)+ expect(estimated.count).not.toBe(-1)- expect(await runCount(db, { table, scoped: true, isReadOnlyContext: true })).toEqual({+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({count: -1,is_estimate: true,})-- // Legacy still exact-counts across all partitions (the pre-fix behavior).- expect(await runCount(db, { table })).toEqual({ count: 45000, is_estimate: false })})withTestDatabase(- 'scoped: small never-analyzed PARTITIONED table -> exact count (both modes)',+ 'small never-analyzed PARTITIONED table -> exact count (writable and read-only)',async (db) => {await db.executeQuery(`create table public.part_small (id int, region text) partition by list (region);@@ -271,18 +241,16 @@ withTestDatabase(expect(await reltuplesOf(db, 'public.part_small')).toBe(-1)const table = await tableOf(db, 'public.part_small', 'part_small', 'public')- expect(await runCount(db, { table, scoped: true })).toEqual({ count: 100, is_estimate: false })- expect(await runCount(db, { table, scoped: true, isReadOnlyContext: true })).toEqual({+ expect(await runCount(db, { table })).toEqual({ count: 100, is_estimate: false })+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({count: 100,is_estimate: false,})})-withTestDatabase(- 'scoped == legacy for an ANALYZED partitioned table below THRESHOLD_COUNT',- async (db) => {- await db.executeQuery(`+withTestDatabase('analyzed partitioned table below THRESHOLD_COUNT is exact', async (db) => {+ await db.executeQuery(`create table public.part_analyzed (id int, region text) partition by list (region);create table public.part_analyzed_e partition of public.part_analyzed for values in ('east');create table public.part_analyzed_w partition of public.part_analyzed for values in ('west');@@ -290,42 +258,38 @@ withTestDatabase(select g, case when g % 2 = 0 then 'east' else 'west' end from generate_series(1, 100) g;analyze public.part_analyzed;`)- const table = await tableOf(db, 'public.part_analyzed', 'part_analyzed', 'public')- expect(await assertScopedEqualsLegacy(db, { table })).toEqual({- count: 100,- is_estimate: false,- })- expect(await assertScopedEqualsLegacy(db, { table, isReadOnlyContext: true })).toEqual({- count: 100,- is_estimate: false,- })- }-)+ const table = await tableOf(db, 'public.part_analyzed', 'part_analyzed', 'public')+ expect(await runCount(db, { table })).toEqual({+ count: 100,+ is_estimate: false,+ })+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({+ count: 100,+ is_estimate: false,+ })+})-withTestDatabase(- 'scoped == legacy for a view flowing through the row-count builder',- async (db) => {- await db.executeQuery(`+withTestDatabase('view flowing through the row-count builder is exact', async (db) => {+ await db.executeQuery(`create table public.view_src (id int primary key);insert into public.view_src select generate_series(1, 7);create view public.v_rows as select * from public.view_src;`)- const table = await tableOf(db, 'public.v_rows', 'v_rows', 'public')-- // A view has no heap (pg_relation_size 0, no partition tree) -> the gate keeps- // an exact count; scoped and legacy agree.- expect(await assertScopedEqualsLegacy(db, { table })).toEqual({ count: 7, is_estimate: false })- expect(await assertScopedEqualsLegacy(db, { table, isReadOnlyContext: true })).toEqual({- count: 7,- is_estimate: false,- })- }-)+ const table = await tableOf(db, 'public.v_rows', 'v_rows', 'public')++ // A view has no heap (pg_relation_size 0, no partition tree) -> the gate keeps+ // an exact count.+ expect(await runCount(db, { table })).toEqual({ count: 7, is_estimate: false })+ expect(await runCount(db, { table, isReadOnlyContext: true })).toEqual({+ count: 7,+ is_estimate: false,+ })+})// ── Fix #1: the embedded estimate select is quoted with literal(), so backslash// identifiers survive regardless of the session's standard_conforming_strings.withTestDatabase(- 'scoped estimate path quotes the embedded select safely (backslash names, scs on & off)',+ 'estimate path quotes the embedded select safely (backslash names, scs on & off)',async (db) => {// Names contain a backslash; in the JS template `\\` is one literal backslash.await db.executeQuery(`@@ -342,28 +306,18 @@ withTestDatabase(const table = { id: Number(id), name: 'wei\\rd', schema: 'public' }const filters: Filter[] = [{ column: 'col\\umn', operator: '=', value: 1 }]- // Default standard_conforming_strings (on): both paths take the estimate- // branch and agree on the value.- const scopedOn = await runCount(db, { table, scoped: true, filters })- expect(scopedOn.is_estimate).toBe(true)- expect(Number.isFinite(scopedOn.count)).toBe(true)- expect(await assertScopedEqualsLegacy(db, { table, filters })).toEqual(scopedOn)+ const scsOn = await runCount(db, { table, filters })+ expect(scsOn.is_estimate).toBe(true)+ expect(Number.isFinite(scsOn.count)).toBe(true)// standard_conforming_strings = off in the SAME connection: the SET, the// CREATE FUNCTION, and the count must share one query (the test uses a pool).const withScsOff = (sql: string) => `set standard_conforming_strings = off;\n${sql}`- const [scopedOff] = await db.executeQuery<CountRow[]>(- withScsOff(getTableRowsCountSql({ table, scoped: true, filters }))+ const [scsOff] = await db.executeQuery<CountRow[]>(+ withScsOff(getTableRowsCountSql({ table, filters })))// literal()/E'...' keeps the backslash identifiers intact under scs=off.- expect(scopedOff.is_estimate).toBe(true)- expect(Number.isFinite(Number(scopedOff.count))).toBe(true)-- // The legacy apostrophe-only escaping mangles the backslashes under scs=off- // (the bug the scoped path fixes), so legacy errors there -- assert only the- // scoped behavior, per contract.- await expect(- db.executeQuery(withScsOff(getTableRowsCountSql({ table, filters })))- ).rejects.toThrow()+ expect(scsOff.is_estimate).toBe(true)+ expect(Number.isFinite(Number(scsOff.count))).toBe(true)})diff --git a/packages/pg-meta/test/sql/studio/table-definition.test.ts b/packages/pg-meta/test/sql/studio/table-definition.test.tsindex 7a82944d5ec..e0152c417e3 100644--- a/packages/pg-meta/test/sql/studio/table-definition.test.ts+++ b/packages/pg-meta/test/sql/studio/table-definition.test.ts@@ -7,7 +7,7 @@ afterAll(async () => {await cleanupRoot()})-test('getTableDefinitionSql (scoped): escapes double quotes in schema, table, column and constraint names', async () => {+test('getTableDefinitionSql: escapes double quotes in schema, table, column and constraint names', async () => {const db = await createTestDatabase()try {await db.executeQuery(`@@ -23,7 +23,7 @@ test('getTableDefinitionSql (scoped): escapes double quotes in schema, table, co`select '"pub""lic2"."te""st"'::regclass::oid::int8 as id;`)- const sql = getTableDefinitionSql({ id, scoped: true })+ const sql = getTableDefinitionSql({ id })const [{ definition }] = await db.executeQuery<{ definition: string }[]>(sql)expect(definition).toContain('"pub""lic2"')@@ -39,7 +39,7 @@ test('getTableDefinitionSql (scoped): escapes double quotes in schema, table, co}})-test('getTableDefinitionSql (scoped): quotes the parent schema for an inherited table', async () => {+test('getTableDefinitionSql: quotes the parent schema for an inherited table', async () => {const db = await createTestDatabase()try {await db.executeQuery(`@@ -53,7 +53,7 @@ test('getTableDefinitionSql (scoped): quotes the parent schema for an inherited`select '"chi""ld1"."chi""ld_tbl"'::regclass::oid::int8 as id;`)- const sql = getTableDefinitionSql({ id, scoped: true })+ const sql = getTableDefinitionSql({ id })const [{ definition }] = await db.executeQuery<{ definition: string }[]>(sql)expect(definition).toContain('INHERITS ("par""ent1"."par""ent_tbl")')diff --git a/packages/pg-meta/test/sql/studio/table-editor.test.ts b/packages/pg-meta/test/sql/studio/table-editor.test.tsindex 3c11fecf3b4..1d14ba90115 100644--- a/packages/pg-meta/test/sql/studio/table-editor.test.ts+++ b/packages/pg-meta/test/sql/studio/table-editor.test.ts@@ -46,15 +46,10 @@ const withTestDatabase = (})}-// The `scoped` flag gates the PR #47894 scoping predicates (default OFF for-// progressive rollout). Both code paths must return semantically identical-// entities; running the same assertions for scoped:true and scoped:false is the-// CI equivalence guard. Once the rollout completes, drop scoped:false here.-for (const scoped of [true, false]) {- withTestDatabase(- `scopes primary keys, unique indexes, relationships and columns to the target table (scoped=${scoped})`,- async ({ executeQuery }) => {- await executeQuery(`+withTestDatabase(+ 'scopes primary keys, unique indexes, relationships and columns to the target table',+ async ({ executeQuery }) => {+ await executeQuery(`create schema if not exists editor_scope;create table editor_scope.authors (@@ -75,58 +70,57 @@ for (const scoped of [true, false]) {);`)- const [{ id: booksId }] = await executeQuery<{ id: number }[]>(- `select 'editor_scope.books'::regclass::oid::int8 as id;`- )-- const sql = getTableEditorSql({ id: booksId, scoped })- const [{ entity }] = await executeQuery<{ entity: Entity }[]>(sql)-- // Basic identity.- expect(entity.id).toBe(booksId)- expect(entity.schema).toBe('editor_scope')- expect(entity.name).toBe('books')-- // Primary key scoped to `books`.- expect(entity.primary_keys).toEqual([- { schema: 'editor_scope', table_name: 'books', table_id: booksId, name: 'id' },- ])-- // Unique index scoped to `books`.- expect(entity.unique_indexes).toHaveLength(1)- expect(entity.unique_indexes[0]).toMatchObject({- schema: 'editor_scope',- table_name: 'books',- table_id: booksId,- columns: ['isbn'],+ const [{ id: booksId }] = await executeQuery<{ id: number }[]>(+ `select 'editor_scope.books'::regclass::oid::int8 as id;`+ )++ const sql = getTableEditorSql({ id: booksId })+ const [{ entity }] = await executeQuery<{ entity: Entity }[]>(sql)++ // Basic identity.+ expect(entity.id).toBe(booksId)+ expect(entity.schema).toBe('editor_scope')+ expect(entity.name).toBe('books')++ // Primary key scoped to `books`.+ expect(entity.primary_keys).toEqual([+ { schema: 'editor_scope', table_name: 'books', table_id: booksId, name: 'id' },+ ])++ // Unique index scoped to `books`.+ expect(entity.unique_indexes).toHaveLength(1)+ expect(entity.unique_indexes[0]).toMatchObject({+ schema: 'editor_scope',+ table_name: 'books',+ table_id: booksId,+ columns: ['isbn'],+ })++ // Relationships include both the outgoing FK (books -> authors) and the+ // incoming FK (reviews -> books).+ expect(entity.relationships).toContainEqual(+ expect.objectContaining({+ source_table_name: 'books',+ source_column_name: 'author_id',+ target_table_name: 'authors',+ target_column_name: 'id',})+ )+ expect(entity.relationships).toContainEqual(+ expect.objectContaining({+ source_table_name: 'reviews',+ source_column_name: 'book_id',+ target_table_name: 'books',+ target_column_name: 'id',+ })+ )- // Relationships include both the outgoing FK (books -> authors) and the- // incoming FK (reviews -> books).- expect(entity.relationships).toContainEqual(- expect.objectContaining({- source_table_name: 'books',- source_column_name: 'author_id',- target_table_name: 'authors',- target_column_name: 'id',- })- )- expect(entity.relationships).toContainEqual(- expect.objectContaining({- source_table_name: 'reviews',- source_column_name: 'book_id',- target_table_name: 'books',- target_column_name: 'id',- })- )-- // Columns: unique flag, check constraint definition, and comment.- const isbnCol = entity.columns.find((c) => c.name === 'isbn')!- expect(isbnCol.is_unique).toBe(true)- expect(isbnCol.comment).toBe('International Standard Book Number')-- const priceCol = entity.columns.find((c) => c.name === 'price')!- expect(priceCol.check).toContain('price > 0')- }- )-}+ // Columns: unique flag, check constraint definition, and comment.+ const isbnCol = entity.columns.find((c) => c.name === 'isbn')!+ expect(isbnCol.is_unique).toBe(true)+ expect(isbnCol.comment).toBe('International Standard Book Number')++ const priceCol = entity.columns.find((c) => c.name === 'price')!+ expect(priceCol.check).toContain('price > 0')+ }+)diff --git a/packages/pg-meta/test/table-privileges.test.ts b/packages/pg-meta/test/table-privileges.test.tsindex 884dfe7ea13..dc2d7a68d0e 100644--- a/packages/pg-meta/test/table-privileges.test.ts+++ b/packages/pg-meta/test/table-privileges.test.ts@@ -92,12 +92,8 @@ type Priv = { grantor: string; grantee: string; privilege_type: string; is_granttype PrivRow = { relation_id: number; schema: string; name: string; privileges: Priv[] }withTestDatabase(- 'scoped tablePrivileges.list/retrieve matches legacy (multiple grantees incl PUBLIC)',+ 'tablePrivileges.list/retrieve surfaces multiple grantees including PUBLIC',async ({ executeQuery }) => {- // Multiple grantees including PUBLIC to exercise the PUBLIC (oid 0) branch of- // the grantee union and multi-grantee aggregation. Roles are cluster-global- // (not dropped by the per-test database cleanup), so guard the creation to- // stay idempotent when the test cluster is reused across runs.await executeQuery(`drop role if exists grantee_a;drop role if exists grantee_b;@@ -109,46 +105,20 @@ withTestDatabase(grant select on public.priv_demo to public;`)- // list(): default and schema-filtered combos. RAW comparison -- no- // normalization, no sorting of rows or the privileges array.- for (const options of [{}, { includedSchemas: ['public'] }, { excludedSchemas: ['public'] }]) {- const legacy = await pgMeta.tablePrivileges.list(options)- const scoped = await pgMeta.tablePrivileges.list({ ...options, scoped: true })- const legacyRes = legacy.zod.parse(await executeQuery(legacy.sql)) as PrivRow[]- const scopedRes = scoped.zod.parse(await executeQuery(scoped.sql)) as PrivRow[]- expect(scopedRes, `list options: ${JSON.stringify(options)}`).toEqual(legacyRes)- }-- // The scoped path must surface the PUBLIC grantee for priv_demo.const { sql, zod } = await pgMeta.tablePrivileges.list({includedSchemas: ['public'],- scoped: true,})const rows = zod.parse(await executeQuery(sql)) as PrivRow[]const demo = rows.find((r) => r.name === 'priv_demo')!expect(demo.privileges.some((p) => p.grantee === 'PUBLIC')).toBe(true)- // retrieve() by id and by schema+name.- const legacyById = await pgMeta.tablePrivileges.retrieve({ id: demo.relation_id })- const scopedById = await pgMeta.tablePrivileges.retrieve({- id: demo.relation_id,- scoped: true,- })- expect(scopedById.zod.parse((await executeQuery(scopedById.sql))[0])).toEqual(- legacyById.zod.parse((await executeQuery(legacyById.sql))[0])- )-- const legacyByName = await pgMeta.tablePrivileges.retrieve({- name: 'priv_demo',- schema: 'public',- })- const scopedByName = await pgMeta.tablePrivileges.retrieve({+ const byId = await pgMeta.tablePrivileges.retrieve({ id: demo.relation_id })+ const byName = await pgMeta.tablePrivileges.retrieve({name: 'priv_demo',schema: 'public',- scoped: true,})- expect(scopedByName.zod.parse((await executeQuery(scopedByName.sql))[0])).toEqual(- legacyByName.zod.parse((await executeQuery(legacyByName.sql))[0])+ expect(byId.zod.parse((await executeQuery(byId.sql))[0])).toEqual(+ byName.zod.parse((await executeQuery(byName.sql))[0]))})diff --git a/packages/pg-meta/test/tables.test.ts b/packages/pg-meta/test/tables.test.tsindex 1a839694873..686b7219f6e 100644--- a/packages/pg-meta/test/tables.test.ts+++ b/packages/pg-meta/test/tables.test.ts@@ -35,9 +35,7 @@ const withTestDatabase = (name: string, fn: (db: TestDb) => Promise<void>) => {})}-// Legacy relationships come out in plan-dependent order (frozen TABLES_SQL has-// no ORDER BY; proven by the adversarial-FK test below), so canonicalize ONLY-// the legacy side to the scoped ORDER BY: constraint_name, then the column names+// Mirrors the tables.retrieve ORDER BY: constraint_name, then the column names// (a composite FK expands to one entry per ordinal column pair).const sortRels = (rels: any[]) =>[...rels].sort(@@ -48,7 +46,7 @@ const sortRels = (rels: any[]) =>)withTestDatabase(- 'scoped tables.retrieve matches legacy (FKs both directions, PK, comment, enums)',+ 'tables.retrieve returns FKs both directions, PK, comment, and enums',async ({ executeQuery }) => {await executeQuery(`create type mood as enum ('sad', 'ok', 'happy');@@ -69,56 +67,34 @@ withTestDatabase(`select 'public.child'::regclass::oid::int8 as child_id;`)- // parent: incoming FK (child.parent_id -> parent.id). child: outgoing FK to- // parent + a self-referential FK. Cover the id and name+schema branches.const cases = [- {- label: 'parent by id',- legacy: { id: Number(parent_id) },- scoped: { id: Number(parent_id), scoped: true },- },- {- label: 'child by name+schema',- legacy: { name: 'child', schema: 'public' },- scoped: { name: 'child', schema: 'public', scoped: true },- },- {- label: 'child by id',- legacy: { id: Number(child_id) },- scoped: { id: Number(child_id), scoped: true },- },+ { label: 'parent by id', ident: { id: Number(parent_id) } },+ { label: 'child by name+schema', ident: { name: 'child', schema: 'public' } },+ { label: 'child by id', ident: { id: Number(child_id) } },] as constfor (const c of cases) {- const legacy = pgMeta.tables.retrieve(c.legacy as any)- const scoped = pgMeta.tables.retrieve(c.scoped as any)- const legacyRow: any = legacy.zod.parse((await executeQuery(legacy.sql))[0])- const scopedRow: any = scoped.zod.parse((await executeQuery(scoped.sql))[0])-- // Everything raw except the legacy relationships array, canonicalized to- // the scoped ORDER BY (legacy order is plan-dependent, see above).- legacyRow.relationships = sortRels(legacyRow.relationships)- expect(scopedRow, c.label).toEqual(legacyRow)- // Scoped's array is already in that order raw (no scoped-side sort).- expect(scopedRow.relationships, c.label).toEqual(sortRels(scopedRow.relationships))+ const { sql, zod } = pgMeta.tables.retrieve(c.ident as any)+ const row: any = zod.parse((await executeQuery(sql))[0])+ expect(row.relationships, c.label).toEqual(sortRels(row.relationships))}- // Sanity: the scoped parent retrieve surfaces the INCOMING FK from child.- const scopedParent = pgMeta.tables.retrieve({ id: Number(parent_id), scoped: true })- const parentRow: any = scopedParent.zod.parse((await executeQuery(scopedParent.sql))[0])+ const parent = pgMeta.tables.retrieve({ id: Number(parent_id) })+ const parentRow: any = parent.zod.parse((await executeQuery(parent.sql))[0])expect(parentRow.relationships.some((r: any) => r.source_table_name === 'child' && r.target_table_name === 'parent')).toBe(true)++ const child = pgMeta.tables.retrieve({ id: Number(child_id) })+ const childRow: any = child.zod.parse((await executeQuery(child.sql))[0])+ expect(childRow.comment).toBe('a child table')})-// Regression proof for the relationships exception: FK creation order (zzz, aaa,-// mmm) differs from constraint_name order, so legacy's plan order cannot match-// scoped's without the legacy-side sort, while scoped is deterministic by name.withTestDatabase(- 'scoped tables.retrieve orders relationships by constraint_name (adversarial)',+ 'tables.retrieve orders relationships by constraint_name (adversarial)',async ({ executeQuery }) => {await executeQuery(`create table public.ref (id int primary key);@@ -127,71 +103,51 @@ withTestDatabase(alter table public.multi add constraint aaa_fk foreign key (b) references public.ref (id);alter table public.multi add constraint mmm_fk foreign key (c) references public.ref (id);`)- const legacy = pgMeta.tables.retrieve({ name: 'multi', schema: 'public' })- const scoped = pgMeta.tables.retrieve({ name: 'multi', schema: 'public', scoped: true })- const legacyRow: any = legacy.zod.parse((await executeQuery(legacy.sql))[0])- const scopedRow: any = scoped.zod.parse((await executeQuery(scoped.sql))[0])+ const { sql, zod } = pgMeta.tables.retrieve({ name: 'multi', schema: 'public' })+ const row: any = zod.parse((await executeQuery(sql))[0])- // Scoped is deterministically constraint_name-ordered, raw.- expect(scopedRow.relationships.map((r: any) => r.constraint_name)).toEqual([+ expect(row.relationships.map((r: any) => r.constraint_name)).toEqual(['aaa_fk','mmm_fk','zzz_fk',])- // Equal only after canonicalizing the (plan-dependent) legacy side.- legacyRow.relationships = sortRels(legacyRow.relationships)- expect(scopedRow).toEqual(legacyRow)})// Composite (multi-column) FK: the relationships subquery expands it to one// entry per ordinal column pair, all sharing constraint_name, so the-// scoped ORDER BY tie-breaks on the column names to stay deterministic.+// ORDER BY tie-breaks on the column names to stay deterministic.withTestDatabase(- 'scoped tables.retrieve orders composite-FK relationship entries deterministically',+ 'tables.retrieve orders composite-FK relationship entries deterministically',async ({ executeQuery }) => {await executeQuery(`create table public.ctgt (x int, y int, primary key (x, y));create table public.csrc (a int, b int, foreign key (b, a) references public.ctgt (x, y));`)- const scoped = pgMeta.tables.retrieve({ name: 'csrc', schema: 'public', scoped: true })- const legacy = pgMeta.tables.retrieve({ name: 'csrc', schema: 'public' })- const scopedRow: any = scoped.zod.parse((await executeQuery(scoped.sql))[0])- const legacyRow: any = legacy.zod.parse((await executeQuery(legacy.sql))[0])+ const { sql, zod } = pgMeta.tables.retrieve({ name: 'csrc', schema: 'public' })+ const row: any = zod.parse((await executeQuery(sql))[0])// Two ordinal pairs, both sharing one constraint_name.- expect(scopedRow.relationships).toHaveLength(2)- expect(new Set(scopedRow.relationships.map((r: any) => r.constraint_name)).size).toBe(1)- // Scoped is already ordered by (name, source col, target col), raw.- expect(- scopedRow.relationships.map((r: any) => [r.source_column_name, r.target_column_name])- ).toEqual([- ['a', 'y'],- ['b', 'x'],- ])- legacyRow.relationships = sortRels(legacyRow.relationships)- expect(scopedRow).toEqual(legacyRow)+ expect(row.relationships).toHaveLength(2)+ expect(new Set(row.relationships.map((r: any) => r.constraint_name)).size).toBe(1)+ expect(row.relationships.map((r: any) => [r.source_column_name, r.target_column_name])).toEqual(+ [+ ['a', 'y'],+ ['b', 'x'],+ ]+ )})withTestDatabase(- 'scoped tables.retrieve preserves composite primary-key column order (indkey, not sorted)',+ 'tables.retrieve preserves composite primary-key column order (indkey, not sorted)',async ({ executeQuery }) => {- // PK declared (b, a) -- index column order is the reverse of alphabetical, so- // an accidental name-sort would be caught here.await executeQuery(`create table public.composite_pk (a int not null, b int not null, c int, primary key (b, a));`)- const scoped = pgMeta.tables.retrieve({ name: 'composite_pk', schema: 'public', scoped: true })- const scopedRow: any = scoped.zod.parse((await executeQuery(scoped.sql))[0])- // Emitted in index (indkey) order (b, a), the semantically meaningful order.- expect(scopedRow.primary_keys.map((pk: any) => pk.name)).toEqual(['b', 'a'])-- // Legacy emits the same PK order (the PK aggregate is ordered identically in- // both renderings), so primary_keys match without any normalization.- const legacy = pgMeta.tables.retrieve({ name: 'composite_pk', schema: 'public' })- const legacyRow: any = legacy.zod.parse((await executeQuery(legacy.sql))[0])- expect(scopedRow.primary_keys).toEqual(legacyRow.primary_keys)+ const { sql, zod } = pgMeta.tables.retrieve({ name: 'composite_pk', schema: 'public' })+ const row: any = zod.parse((await executeQuery(sql))[0])+ expect(row.primary_keys.map((pk: any) => pk.name)).toEqual(['b', 'a'])})@@ -751,6 +707,27 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {{"bytes": Any<Number>,"columns": [+ {+ "check": null,+ "comment": null,+ "data_type": "integer",+ "default_value": "nextval('memes_id_seq'::regclass)",+ "enums": [],+ "format": "int4",+ "format_schema": "pg_catalog",+ "id": "16510.1",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "id",+ "ordinal_position": 1,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },{"check": null,"comment": null,@@ -835,27 +812,6 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {"table": "memes","table_id": 16510,},- {- "check": null,- "comment": null,- "data_type": "integer",- "default_value": "nextval('memes_id_seq'::regclass)",- "enums": [],- "format": "int4",- "format_schema": "pg_catalog",- "id": "16510.1",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "id",- "ordinal_position": 1,- "schema": "public",- "table": "memes",- "table_id": 16510,- },{"check": null,"comment": null,@@ -933,6 +889,27 @@ withTestDatabase('retrieve table by name and schema', async ({ executeQuery }) ={"bytes": Any<Number>,"columns": [+ {+ "check": null,+ "comment": null,+ "data_type": "integer",+ "default_value": "nextval('memes_id_seq'::regclass)",+ "enums": [],+ "format": "int4",+ "format_schema": "pg_catalog",+ "id": "16510.1",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "id",+ "ordinal_position": 1,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },{"check": null,"comment": null,@@ -1017,27 +994,6 @@ withTestDatabase('retrieve table by name and schema', async ({ executeQuery }) ="table": "memes","table_id": 16510,},- {- "check": null,- "comment": null,- "data_type": "integer",- "default_value": "nextval('memes_id_seq'::regclass)",- "enums": [],- "format": "int4",- "format_schema": "pg_catalog",- "id": "16510.1",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "id",- "ordinal_position": 1,- "schema": "public",- "table": "memes",- "table_id": 16510,- },{"check": null,"comment": null,diff --git a/packages/pg-meta/test/types.test.ts b/packages/pg-meta/test/types.test.tsindex ad548ec2d30..0a2ae08e314 100644--- a/packages/pg-meta/test/types.test.ts+++ b/packages/pg-meta/test/types.test.ts@@ -103,11 +103,8 @@ const OPTION_MATRIX = []withTestDatabase(- 'scoped types.list matches legacy for all option combos (enums, composites, dropped attrs, array types)',+ 'types.list is oid-ordered and handles enums, composites, and dropped attrs',async ({ executeQuery }) => {- // Fixture coverage: multi-label enum with a NON-alphabetical label order (so- // enumsortorder matters), a composite type with a dropped attribute, and a- // composite referencing the enum.await executeQuery(`create type color as enum ('red', 'green', 'blue', 'yellow');create type shipment as (id int8, note text, tossme int, color color);@@ -115,26 +112,14 @@ withTestDatabase(create type point3 as (x float8, y float8, z float8);`)- // Legacy types.list has no ORDER BY (plan-dependent row order), so sort ONLY- // the legacy side by id (t.oid) to match the scoped `order by t.oid`.for (const { label, options } of OPTION_MATRIX) {- const legacy = await pgMeta.types.list(options)- const scoped = await pgMeta.types.list({ ...options, scoped: true })-- const legacyRes = [...legacy.zod.parse(await executeQuery(legacy.sql))].sort(- (a, b) => a.id - b.id- )- const scopedRes = scoped.zod.parse(await executeQuery(scoped.sql))-- expect(scopedRes, `option combo: ${label}`).toEqual(legacyRes)- // Scoped is already in t.oid order raw (no scoped-side sort).- const scopedIds = scopedRes.map((t) => t.id)- expect(scopedIds, `${label} oid-ordered`).toEqual([...scopedIds].sort((a, b) => a - b))+ const { sql, zod } = await pgMeta.types.list(options)+ const res = zod.parse(await executeQuery(sql))+ const ids = res.map((t) => t.id)+ expect(ids, `${label} oid-ordered`).toEqual([...ids].sort((a, b) => a - b))}- // Sanity: the enum/composite fixtures actually surface with correct- // ordering + dropped-attribute handling in the scoped path.- const { sql, zod } = await pgMeta.types.list({ includedSchemas: ['public'], scoped: true })+ const { sql, zod } = await pgMeta.types.list({ includedSchemas: ['public'] })const res = zod.parse(await executeQuery(sql))expect(res.find((t) => t.name === 'color')?.enums).toEqual(['red', 'green', 'blue', 'yellow'])expect(res.find((t) => t.name === 'shipment')?.attributes.map((a) => a.name)).toEqual([